LeetCode 344 Reverse String

题意

翻转字符串。

解法

两个指针,分别在首和尾,都向中间走,直到首超过尾。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public String reverseString(String s) {
char[] chars = s.toCharArray();
for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
return new String(chars);
}
}

Runtime: 2 ms, faster than 79.62% of Java online submissions for Reverse String.