0557. Reverse Words in a String iii #
题目 #
- 给定字符串
s
,反转字符串中每个单词的字符顺序,同时保留空格和单词的初始顺序。
思路 #
双指针 #
代码 #
双指针 #
class Solution {
public String reverseWords(String s) {
String[] words = s.split(" ");
for (int i = 0; i < words.length; i++) {
char[] charArray = words[i].toCharArray();
int left = 0, right = charArray.length - 1;
while (left < right) {
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
left++; right--;
}
words[i] = String.valueOf(charArray);
}
String ans = words[0];
for (int i = 1; i < words.length; i++) ans += " " + words[i];
return ans;
}
}