-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
42 lines (41 loc) · 1.09 KB
/
Solution.java
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
public class Solution {
public String reverseWords(String s) {
if (s.length()<1) {
return s;
}
String a = "";
String answer = "";
boolean flag=true;
for (int i = s.length() - 1; i >= 0; i--) {
String k = s.substring(i, i + 1);
if (flag) {
if (k.equals(" ")) {
}else {
flag=false;
a=k+a;
}
}else {
if (k.equals(" ")) {
flag=true;
answer=answer+" "+a;
a="";
}else {
a=k+a;
}
}
}
if (a.length()!=0) {
answer=answer+" "+a;
}
if (answer.length()==0) {
return "";
}
while (answer.substring(0,1).equals(" ")) {
if (answer.length()==1) {
return "";
}
answer=answer.substring(1, answer.length());
}
return answer;
}
}