abc de先整个翻转:
ed cba再逐个单词翻转:
de abc就是要求的结果。
public class Solution
{
public void reverseWords(char[] s)
{
if(s.length <= 1) return;
int l = 0;
int r = s.length-1;
reverse(s,l,r);
l = 0;
r = 0;
for(r = 0; r < s.length;r++)
{
if(s[r] == ' ')
{
reverse(s,l,r-1);
l = r+1;
}
}
r--;
reverse(s,l,r);
}
public void reverse(char[] s, int l, int r)
{
char c = ' ';
while(l < r)
{
c = s[l];
s[l] = s[r];
s[r] = c;
l++;
r--;
}
}
}
二刷。
有印象是二次翻转。
边界条件要仔细。。
Time: O(n)
Space: O(n) in-place
public class Solution {
public void reverseWords(char[] s) {
if (s.length <= 1) return;
int r = 0;
int l = 0;
while (r < s.length) {
while (r < s.length && s[r] != ' ') r++;
reverse(s, l, r-1);
l = r+1;
r++;
}
reverse(s, 0, s.length - 1);
}
public void reverse(char[] s, int l, int r) {
while (l < r) {
char c = s[l];
s[l++] = s[r];
s[r--] = c;
}
return;
}
}