Reverse Words in a String II
Input:
["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output:
["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]Analysis
Solution
Last updated
Input:
["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output:
["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]Last updated
class Solution {
public void reverseWords(char[] str) {
// reverse the whole input
reverse(str, 0, str.length - 1);
// reverse each individual word
reverseEachWords(str);
}
void reverse(char[] str, int s, int t) {
while (s < t) {
char tmp = str[s];
str[s] = str[t];
str[t] = tmp;
s++;
t--;
}
}
void reverseEachWords(char[] str) {
int i = 0, j = 0;
int n = str.length;
while (i < n && j < n) {
while (i < n && str[i] == ' ') {
i++;
}
j = i;
while (j < n && str[j] != ' ') {
j++;
}
reverse(str, i, j - 1);
i = j;
}
}
}public void reverseWords(char[] s){
reverseWords(s,0,s.length-1);
for(int i = 0, j = 0;i <= s.length;i++){
if(i==s.length || s[i] == ' '){
reverseWords(s,j,i-1);
j = i+1;
}
}
}
private void reverseWords(char[] s, int begin, int end){
while(begin < end){
char c = s[begin];
s[begin] = s[end];
s[end] = c;
begin++;
end--;
}
}