Skip to content

Commit ddf8758

Browse files
solves reverse words in a string
1 parent 8b4fdc8 commit ddf8758

File tree

3 files changed

+21
-4
lines changed

3 files changed

+21
-4
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@
134134
| 147 | [Insertion Sort List](https://leetcode.com/problems/insertion-sort-list) | [![Java](assets/java.png)](src/InsertionSortList.java) | |
135135
| 148 | [Sort List](https://leetcode.com/problems/sort-list) | [![Java](assets/java.png)](src/SortList.java) | |
136136
| 150 | [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation) | [![Java](assets/java.png)](src/EvaluateReversePolishNotation.java) | |
137-
| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string) | | |
137+
| 151 | [Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string) | [![Java](assets/java.png)](src/ReverseWordsInAString.java) | |
138138
| 152 | [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray) | | |
139139
| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array) | | |
140140
| 155 | [Min Stack](https://leetcode.com/problems/min-stack) | [![Java](assets/java.png)](src/MinStack.java) [![Python](assets/python.png)](python/min_stack.py) | |

Diff for: src/HelloWorld.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
public class HelloWorld {
22
public static void main(String[] args) {
3-
System.out.println(Integer.parseInt("2"));
4-
System.out.println(Integer.parseInt("-11"));
5-
System.out.println(EvaluateReversePolishNotation.evalRPN(new String[] {"2", "-11", "-"}));
3+
System.out.println(ReverseWordsInAString.reverseWords(" hello world "));
64
}
75
}

Diff for: src/ReverseWordsInAString.java

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/reverse-words-in-a-string
2+
// T: O(s)
3+
// S: O(s)
4+
5+
public class ReverseWordsInAString {
6+
private static final char SPACE = ' ';
7+
8+
public static String reverseWords(String s) {
9+
final String[] words = s.split(" ");
10+
final StringBuilder result = new StringBuilder();
11+
for (int i = words.length - 1 ; i >= 0 ; i--) {
12+
String word = words[i];
13+
if (word.isEmpty()) continue;
14+
result.append(word).append(SPACE);
15+
}
16+
result.deleteCharAt(result.length() - 1);
17+
return result.toString();
18+
}
19+
}

0 commit comments

Comments
 (0)