forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_151.java
64 lines (59 loc) · 1.97 KB
/
_151.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.fishercoder.solutions;
import java.util.ArrayDeque;
import java.util.Deque;
public class _151 {
public static class Solution1 {
public String reverseWords(String s) {
s.trim();
if (s == null || s.length() == 0) {
return "";
}
String[] words = s.split(" ");
if (words == null || words.length == 0) {
return "";
}
Deque<String> stack = new ArrayDeque<>();
for (String word : words) {
if (!word.equals("")) {
stack.offer(word);
}
}
StringBuilder stringBuilder = new StringBuilder();
while (!stack.isEmpty()) {
stringBuilder.append(stack.pollLast()).append(" ");
}
return stringBuilder.substring(0, stringBuilder.length() - 1).toString();
}
}
public static class Solution2 {
public String reverseWords(String s) {
int len = s.length();
int i = 0;
int j = 0;
String result = "";
while (i < len) {
// index i keeps track of the spaces and ignores them if found
while (i < len && s.charAt(i) == ' ') {
i++;
}
if (i == len) {
break;
}
j = i + 1;
// index j keeps track of non-space characters and gives index of the first occurrence of space after a non-space character
while (j < len && s.charAt(j) != ' ') {
j++;
}
// word found
String word = s.substring(i, j);
if (result.length() == 0) {
result = word;
} else {
result = word + " " + result;
}
i = j + 1;
}
return result;
}
}
}