class Solution {
public String reverseWords(String s) {
StringBuilder sb = removeSpace(s);
reverseString(sb,0,sb.length()-1);
reverseEachWord(sb);
return sb.toString();
}
private void reverseEachWord(StringBuilder sb){
int start = 0;
int end = 1;
int n = sb.length();
while(start<n){
while(end<n && sb.charAt(end)!=' '){
end++;
}
reverseString(sb,start,end-1);
start=end+1;
end=start+1;
}
}
private void reverseString(StringBuilder sb,int start,int end){
while(start<end){
char c = sb.charAt(start);
sb.setCharAt(start,sb.charAt(end));
sb.setCharAt(end,c);
start++;
end--;
}
}
private StringBuilder removeSpace(String s){
int start=0;
int end = s.length()-1;
while(s.charAt(start) ==' ') start++;
while(s.charAt(end) ==' ') end--;
StringBuilder sb = new StringBuilder();
while(start<=end){
char c = s.charAt(start);
if(c!=' ' || sb.charAt(sb.length()-1)!=' '){
sb.append(c);
}
start++;
}
return sb;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54