给定一个字符串,逐个翻转字符串中的每个单词。
您在真实的面试中是否遇到过这个题?
Yes
样例
给出s = "the sky is blue",返回"blue is sky the"
说明
标签
Expand
- 单词的构成:无空格字母构成一个单词
- 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
- 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个
相关题目 Expand
思想:先将整个字符串以空格划分保存在arr,再遍历arr将非空格的word逆序放到arrword数组中,再遍历arrword。
public class Solution {
/**
* @param s : A string
* @return : A string
*/
public String reverseWords(String s) {
// write your code
if (null == s || 0 == s.length())
return s;
String[] arrs = s.split(" ");
StringBuffer result = new StringBuffer();
String[] arrWord = new String[arrs.length];
int k = arrWord.length - 1;
for (int i = 0; i < arrs.length; i++) {
if (arrs[i] != " ") {
arrWord[k--] = arrs[i];
}
}
for (int i = 0; i < arrWord.length; i++) {
if (i == arrWord.length - 1) {
result.append(arrWord[i]);
} else if (arrWord[i] != null || arrWord[i].length() != 0) {
result.append(arrWord[i] + " ");
}
}
return result.toString();
}
}
/**
* @param s : A string
* @return : A string
*/
public String reverseWords(String s) {
// write your code
if (null == s || 0 == s.length())
return s;
String[] arrs = s.split(" ");
StringBuffer result = new StringBuffer();
String[] arrWord = new String[arrs.length];
int k = arrWord.length - 1;
for (int i = 0; i < arrs.length; i++) {
if (arrs[i] != " ") {
arrWord[k--] = arrs[i];
}
}
for (int i = 0; i < arrWord.length; i++) {
if (i == arrWord.length - 1) {
result.append(arrWord[i]);
} else if (arrWord[i] != null || arrWord[i].length() != 0) {
result.append(arrWord[i] + " ");
}
}
return result.toString();
}
}