Skip to content

Commit

Permalink
add 42
Browse files Browse the repository at this point in the history
  • Loading branch information
CaiFengGH authored Apr 18, 2018
1 parent 62589bc commit 2f766a1
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions CodingInterview/42-反转句子.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
>题目
反转句子;

- 实现方法

两次反转,且注意多空格情况;

```
package DayCode;
/**
* @author Ethan
* @desc 反转句子中单词
*/
public class C42ReverseWords {
/**
* @author Ethan
* @desc 两次反转,第一次反转整个句子,第二次反转每个单词
*/
public String reverseWords(String str){
//1-异常参数检测
if(str == null || str.length() == 0){
return null;
}
//2-第一次反转
String res = reverse(str.trim());
String[] resArr = res.split(" +");
StringBuilder sb = new StringBuilder();
//3-第二次反转
for(int i = 0; i < resArr.length - 1; i++){
sb.append(reverse(resArr[i]) + " ");
}
sb.append(reverse(resArr[resArr.length - 1]));
return sb.toString();
}
public String reverse(String str){
StringBuilder sb = new StringBuilder();
for(int i = str.length() - 1; i >= 0; i--){
sb.append(str.charAt(i));
}
return sb.toString();
}
}
```

0 comments on commit 2f766a1

Please sign in to comment.