-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-151-Reverse-Words-in-a-String.java
More file actions
52 lines (40 loc) · 1.48 KB
/
LeetCode-151-Reverse-Words-in-a-String.java
File metadata and controls
52 lines (40 loc) · 1.48 KB
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
/*
LeetCode: https://leetcode.com/problems/reverse-words-in-a-string/
LintCode: http://www.lintcode.com/problem/reverse-words-in-a-string/
JiuZhang: http://www.jiuzhang.com/solutions/reverse-words-in-a-string/
ProgramCreek: http://www.programcreek.com/2014/02/leetcode-reverse-words-in-a-string-java/
Analysis:
*/
class Solution {
// 1.
/*
Runtime: 1 ms, faster than 99.93% of Java online submissions for Reverse Words in a String.
*/
// public String reverseWords(String s) {
// s = s.trim();
// String[] arr = s.split(" ");
// StringBuilder sb = new StringBuilder();
// for (int i = arr.length - 1; i >= 0; i--) {
// if ("".equals(arr[i])) continue;
// sb.append(arr[i]);
// if (i != 0) sb.append(" ");
// }
// return sb.toString();
// }
// 2.
/*
Runtime: 1 ms, faster than 99.93% of Java online submissions for Reverse Words in a String.
*/
public String reverseWords(String s) {
if(s == null || s.length() == 0) return s;
s = s.trim();
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = strs.length - 1; i >=0; i--){
if(!strs[i].equals("")){
sb.append(strs[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1); //remove the last " "
}
}