-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_words_in_string.java
More file actions
39 lines (35 loc) · 967 Bytes
/
Copy pathreverse_words_in_string.java
File metadata and controls
39 lines (35 loc) · 967 Bytes
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
class Solution {
public String reverseWords(String s) {
// TLE
// s+=" ";
// String ans="";
// for(int i=0;i<s.length();i++)
// {
// String word="";
// while(s.charAt(i)!=' ')
// {
// word+=s.charAt(i);
// }
// ans=word+""+ans;
// }
// return ans;
// String[] words=s.trim().split(" ");
// String ans="";
// for(int i=words.length-1;i>=0;i--)
// {
// if(words[i]!=" ")
// ans+=words[i]+" ";
// }
// return ans.trim();
StringBuilder sb=new StringBuilder();
int len=s.length();
for(int i=s.length()-1;i>=0;i--){
if(s.charAt(i)==' '){
sb.append(s.substring(i,len));
len=i;
}
}
sb.append(' '+s.substring(0,len));
return sb.toString().replaceAll("\s+"," ").trim();
}
}