This problem is pretty straightforward. We first split the string to words array, and then iterate through the array and add each element to a new string.
classSolution {
publicvoidreverseWords(String s) {
int i = 0;
int n = s.length();
char a = s.toCharArrya();
for (int j = 0; j < n; j++) {
if (a[j]==' ') {
reverse(a, i, j - 1);
i = j + 1;
}
}
reverse(a, i, n - 1);
reverse(s, 0, n - 1);
}
privatevoidreverse(char[] a, int i, int j) {
while (i < j) {
char t = a[i];
a[i++]= a[j];
a[j--]= t;
}
}
}
1
2
3
4
5
6
7
8
9
10
privatevoidswap(char[] s, int i, int j){
char temp = s[i];
s[i]=s[j];
s[j]=temp;
}
privatevoidreverse(char[] s, int i, int j){
while(i<j){
swap(i++, j--)
}
}