-
Notifications
You must be signed in to change notification settings - Fork 232
/
ReverseWords.java
executable file
·65 lines (53 loc) · 1.53 KB
/
ReverseWords.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 Algorithms.string;
public class ReverseWords {
public static void main(String[] strs) {
reverseWords(" I love cmu ");
}
/**
* @param s : A string
* @return : A string
*/
public static String reverseWords(String s) {
// write your code
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
//System.out.println(s);
// remove the leading and the tail space.
String sTrim = s.trim();
String[] strs = sTrim.split("\\s+");
for (int i = strs.length - 1; i >= 0; i--) {
System.out.println("word:" + strs[i]);
if (strs[i].equals("")) {
continue;
}
sb.append(strs[i]);
if (i != 0) {
sb.append(" ");
}
}
return sb.toString();
}
/**
* @param s : A string
* @return : A string
*/
public String reverseWords1(String s) {
// write your code
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
// remove the leading and the tail space.
String sTrim = s.trim();
String strs[] = sTrim.split("\\s+");
for (int i = strs.length - 1; i >= 0; i--) {
sb.append(strs[i]);
if (i != 0) {
sb.append(" ");
}
}
return sb.toString();
}
}