344. Reverse String
Problem
1
2
3
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Questions before reading example
- ”s” can be empty? nope
- ”s” max length? 10^5
- ”s” only english? yes
Example
1
2
3
4
5
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Solution
1
2
3
4
5
6
7
8
9
10
class Solution {
public void reverseString(char[] s) {
for (int i = 0; i < s.length / 2; i++) {
char tmp = s[i];
s[i] = s[s.length - 1 - i];
s[s.length - 1 - i] = tmp;
}
}
}
Spent time
- 13분
Review
- 생각나는 그대로 풀었는데 다행히 잘 풀렸다.
- index 를 다루는건 늘 조심스럽다.