Problem
Write a function that takes a string as input and returns the string reversed.
Example 1:
Input: "hello"
Output: “olleh”
Example 2:
Input: "A man, a plan, a canal: Panama"
Output: “amanaP :lanac a ,nalp a ,nam A”
Solution 1
Analysis
Use two pointers i
,j
. i
iterates characters from left to the center and j
iterates from right to the center, then exchange the values i
and j
points at.
Python implenmentation
|
|
Java implementation
|
|
Time complexity
O(n).
Space complexity
O(n).
Solution 2
Analysis
Iterate characters in string s
backwards.
Python implementation
|
|
Java implementation
|
|
Time complexity
O(n).
Space complexity
O(1).
Link
344. Reverse String
(中文版) 算法笔记: 力扣#344 反转字符串
近期评论