Skip to content

Commit a9a231d

Browse files
authored
Merge pull request gzc426#109 from MMzhe/patch-2
Create sourcema.md
2 parents 717d3c1 + 488e172 commit a9a231d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

2018.11.28-leetcode151/sourcema.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# LeetCode 151
2+
1. public static String reverseWords(String s) {//first method
3+
if (s.length() == 0 || s == null) {
4+
return s;
5+
}
6+
String str = s.trim();
7+
String[] split = str.split(" +");
8+
String result = "";
9+
for (int i = split.length - 1; i >=0; i--) {
10+
result += split[i] + " ";
11+
}
12+
return result.substring(0, result.length() - 1);
13+
}
14+
2. public static String reverseWords2(String s) {//two method
15+
if (s.length() == 0 || s == null) {
16+
return s;
17+
}
18+
String str = s.trim();//" "此时str为""
19+
char[] chars = str.toCharArray();
20+
reverse(chars, 0, chars.length - 1);
21+
//String target = new StringBuilder(str).reverse().toString();
22+
String result = "";
23+
int left=0,right=0;
24+
//char[] chars = target.toCharArray();
25+
while (right < chars.length) {
26+
while (right<chars.length&&chars[right] != ' ') {
27+
right++;
28+
}
29+
reverse(chars, left, right - 1);
30+
result+=String.valueOf(Arrays.copyOfRange(chars, left, right))+" ";
31+
while (right < chars.length && chars[right] == ' ') {
32+
right++;
33+
}
34+
left=right;
35+
}
36+
return result.length()==0?result:result.substring(0,result.length()-1);
37+
}
38+
39+
private static void reverse(char[] chars, int i, int j) {
40+
while (i < j) {
41+
swap(chars, i++, j--);
42+
}
43+
}
44+
45+
private static void swap(char[] chars, int i, int j) {
46+
char ch = chars[i];
47+
chars[i] = chars[j];
48+
chars[j] = ch;
49+
}

0 commit comments

Comments
 (0)