forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path151_Reverse_words_in_string
45 lines (37 loc) · 1.02 KB
/
151_Reverse_words_in_string
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
// https://leetcode.com/problems/reverse-words-in-a-string/
// MY approach
class Solution {
public String reverseWords(String s) {
if (s.length() == 0 || s.equals("") || s.equals(" "))
return "";
StringBuffer sb = new StringBuffer();
int i = 0;
String tmp = "";
int f = 0;
while(i < s.length()) {
while (i<s.length() && s.charAt(i)!=' ') {
tmp += s.charAt(i);
f = 1;
i++;
}
if (f == 1) {
sb.insert(0,tmp+" ");
tmp = "";
f = 0;
}
i++;
}
if (sb.length() > 0) {
while (sb.charAt(sb.length()-1)==' ')
sb.deleteCharAt(sb.length()-1);
}
return sb.toString();
}
}
// best
String[] parts = s.trim().split("\\s+");
String out = "";
for (int i = parts.length - 1; i > 0; i--) {
out += parts[i] + " ";
}
return out + parts[0];