Skip to content

Commit c28ff43

Browse files
authored
Merge pull request gzc426#219 from ieei/master
ieei
2 parents 84f6add + 4874f8b commit c28ff43

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

2018.11.28-leetcode151/ieei.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
public class Solution {
2+
public String reverseWords(String s) {
3+
int length=s.length();
4+
//当字符串为空
5+
if(s == null){ return null;}
6+
//当字符串为" "时 直接返回null
7+
if(s.trim().equals("")){
8+
return s.trim();
9+
}
10+
/**
11+
* 先将字符串按照空格分裂为字符串数组
12+
* 然后收尾两个指针来交换即可
13+
*/
14+
//0.掐头去尾
15+
String allRevStr=s.trim();
16+
//1.将字符串按照空格分裂为字符串数组
17+
String[] strChar=allRevStr.split(" ");
18+
19+
//2.使用首尾两个指针来交换
20+
int left=0;
21+
int right=strChar.length-1;
22+
String temStr=null;
23+
while(left<right){
24+
//交换
25+
temStr=strChar[left];
26+
strChar[left]=strChar[right];
27+
strChar[right]=temStr;
28+
//移动指针
29+
left++;
30+
right--;
31+
}
32+
//3.拼接好新的字符串
33+
String reverse="";
34+
for (int i=0; i<strChar.length; ++i) {
35+
//对每一个单词掐头去尾
36+
String temp=strChar[i].trim();
37+
38+
if (temp.equals("")) {
39+
continue;
40+
}
41+
42+
if (i==strChar.length-1) {
43+
reverse=reverse+temp;
44+
}else{
45+
reverse=reverse+temp+" ";
46+
}
47+
}
48+
return reverse;
49+
}
50+
}

0 commit comments

Comments
 (0)