-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverseWords.java
More file actions
42 lines (34 loc) · 1.35 KB
/
reverseWords.java
File metadata and controls
42 lines (34 loc) · 1.35 KB
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
/* Given an input string, reverse the string word by word.
Example:
Given s = "the sky is blue",
return "blue is sky the".
A sequence of non-space characters constitutes a word.
Your reversed string should not contain leading or trailing spaces, even if it is present in the input string.
If there are multiple spaces between words, reduce them to a single space in the reversed string.
*/
public String reverseWords(String a) {
if(a.isEmpty() || a==null)
return "";
StringBuffer stringBuffer = new StringBuffer(a);
stringBuffer.reverse();
int i=0;
String retString="";
while(i<stringBuffer.length())
{
if(stringBuffer.charAt(i)==' '){
retString += stringBuffer.charAt(i);
i++;
}
else
{
StringBuffer b = new StringBuffer();
while(i<stringBuffer.length() && stringBuffer.charAt(i)!=' ')
{
b.append(stringBuffer.charAt(i));
i++;
}
retString+=b.reverse();
}
}
return retString;
}