344 Reverse String

1. Question

Write a function that takes a string as input and returns the string reversed.
Example: Given s = "hello", return "olleh".

2. Implementation

(1) Two Pointers
1
class Solution {
2
public String reverseString(String s) {
3
int start = 0, end = s.length() - 1;
4
char[] letters = s.toCharArray();
5
6
while (start < end) {
7
char temp = letters[start];
8
letters[start] = letters[end];
9
letters[end] = temp;
10
++start;
11
--end;
12
}
13
return new String(letters);
14
}
15
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n), 空间复杂度O(1)