目录
2. 反转字符串中的单词 III(LeetCode 557 题)
1. 反转字符串(LeetCode 344 题)
1.1题目
1.2思路
最好的方法就是循环双指针,一个指头一个指尾。然后头++尾--互相交换数据。时间复杂度为n,空间复杂度为1.
class Solution {
public void reverseString(char[] s) {
int i=0,j=s.length-1;
while(i<j){
char temp = s[i];
s[i++] = s[j];
s[j--] = temp;
}
}
}
2. 反转字符串中的单词 III(LeetCode 557 题)
2.1题目
2.2思路
接上题的思路,其实就是把字符串拆成了许多个单词进行反转,与上题思路相同。
设置end和front指针。front为0.
以i为指针循环字符串,如果遇到空格更新end为i-1。然后进行双指针字符串反转。接下来更新front。
最后循环完再遍历一次。
class Solution {
public String reverseWords(String s) {
int front = 0;
int end = 0;
char[] status = s.toCharArray();
for(int i=0;i<status.length;i++){
if (status[i]!=' '){
continue;
}
else {
end = i-1;
while (front<end){
char temp = status[front];
status[front] = status[end];
status[end] = temp;
front++;
end--;
}
if (i+1!=status.length){
front = i+1;
}
}
}
end = status.length-1;
while (front<end){
char temp = status[front];
status[front] = status[end];
status[end] = temp;
front++;
end--;
}
return String.valueOf(status);
}
}