forked from CaiFengGH/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} | ||
``` |