From : www.LeetCode.com
Description
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note:
In the string, each word is separated by single space and there will not be any extra space in the string.
中文介绍
描述
给定一个字符串,将该字符串中的每一个单词都反转,但是保留原来的空格和单词顺序。
例子
输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"
注意:
每两个单词之间,有且只能有一个空格,而且整个字符串的两段是没有空格的,
解决方案一
本方案的思想:
首先,需要将整个字符串通过空格分割成若干个单词(存放在字符串数组中),注意,原字符串中,两个单词之间,不一定只有一个空格。因此需要用到正则表达式来分割“\s+”代表一个或多个空格。
然后,直接使用API来反转字符串数组中的每个单词,并拼接起来。
拼接的时候要注意,整个字符串的两端时没有空格的。
代码实现(JAVA)
class Solution {
public String reverseWords(String s) {
// 通过一个或多个空格分割字符串
String[] str = s.split("\\s+");
s = "";
// 分别将每一段字符串反转,并接到s上
for (int i = 0; i < str.length; i++) {
if (i < str.length - 1) {
s += new StringBuilder(str[i]).reverse().toString() + " ";
}else{
s += new StringBuilder(str[i]).reverse().toString();
}
}
return s;
}
}
总结
要注意到原始字符串中两个单词之间可能不止一个空格。
还有就是拼接的时候要注意两端不能有空格。