File tree Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Expand file tree Collapse file tree 2 files changed +23
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+ /**Given an input string, reverse the string word by word.
3
+
4
+ For example,
5
+ Given s = "the sky is blue",
6
+ return "blue is sky the".*/
7
+ public class ReverseWordsinaString {
8
+ public String reverseWords (String s ) {
9
+ if (!s .contains (" " )) return s ;//for cases like this: "a"
10
+ if (s .matches (" *" )) return "" ;//for cases like this: " "
11
+ String [] words = s .split (" " );
12
+ StringBuilder sb = new StringBuilder ();
13
+ for (int i = words .length -1 ; i >= 0 ; i --){
14
+ if (!words [i ].equals ("" ) && !words [i ].equals (" " )){
15
+ sb .append (words [i ]);
16
+ sb .append (" " );
17
+ }
18
+ }
19
+ sb .deleteCharAt (sb .length ()-1 );
20
+ return sb .toString ();
21
+ }
22
+ }
Original file line number Diff line number Diff line change 38
38
| 165| [ Compare Version Numbers] ( https://leetcode.com/problems/compare-version-numbers/ ) | [ Solution] ( ../../blob/master/EASY/src/easy/CompareVersionNumbers.java ) | O(n)| O(1) | Easy|
39
39
| 162| [ Find Peak Element] ( https://leetcode.com/problems/find-peak-element/ ) | [ Solution] ( ../../blob/master/MEDIUM/src/medium/FindPeakElement.java ) | O(1) | O(logn)/O(n) | Binary Search|
40
40
|155|[ Min Stack] ( https://leetcode.com/problems/min-stack/ ) |[ Solution] ( ../../blob/master/EASY/src/easy/MinStack.java ) | O(1)|O(n) | Easy| Stack
41
+ | 151| [ Reverse Words in a String] ( https://leetcode.com/problems/reverse-words-in-a-string/ ) | [ Solution] ( ../../blob/master/MEDIUM/src/medium/ReverseWordsinaString.java ) | O(n)| O(n) | Medium|
41
42
|140|[ Word Break II] ( https://leetcode.com/problems/word-break-ii/ ) |[ Solution] ( ../../blob/master/HARD/src/hard/WordBreakII.java ) | ? |O(n^2) | Hard| Backtracking/DFS
42
43
|139|[ Word Break] ( https://leetcode.com/problems/word-break/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/WordBreak.java ) | O(n^2)|O(n) | Medium| DP
43
44
|133|[ Clone Graph] ( https://leetcode.com/problems/clone-graph/ ) |[ Solution] ( ../../blob/master/MEDIUM/src/medium/CloneGraph.java ) | O(n)|O(n) | Medium| HashMap, BFS
You can’t perform that action at this time.
0 commit comments