Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
public String reverseWords(String s) {
String newString = s.trim();
if(newString.length()<=0) return s.trim();
String []splitsStrings = newString.split(" ");
int len = splitsStrings.length;
StringBuilder sBuilder = new StringBuilder("");
for(int i=len-1;i>=0;i--){
if(splitsStrings[i].length()>0){
sBuilder.append(splitsStrings[i]);
sBuilder.append(" ");
}
}
String resultString = sBuilder.toString();
return resultString.trim();
}
-
public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.If this
Stringobject represents an empty character sequence, or the first and last characters of character sequence represented by thisStringobject both have codes greater than'\u0020'(the space character), then a reference to thisStringobject is returned.Otherwise, if there is no character with a code greater than
'\u0020'in the string, then a newStringobject representing an empty string is created and returned.Otherwise, let k be the index of the first character in the string whose code is greater than
'\u0020', and let m be the index of the last character in the string whose code is greater than'\u0020'. A newStringobject is created, representing the substring of this string that begins with the character at indexk and ends with the character at index m-that is, the result ofthis.substring(k, m+1).This method may be used to trim whitespace (as defined above) from the beginning and end of a string.
-
Returns:
- A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
-
StringBuilder
public StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is16plus the length of the string argument.-
Parameters:
-
str- the initial contents of the buffer.
Throws:
-
NullPointerException- ifstrisnull
-
Analysis:
void reverseWords(string &s) {
string word;//tmp string to store each word
string res;// result string
int i = 0;
for(int i=0;i<s.size();i++){
if(s[i]==' ' && word.empty()) continue;//multiple spaces
if(s[i]==' ' && !word.empty()){// word ends
res = word+" "+res;// add word to result string
word = "";// reset the word
continue;
}
if(s[i]!=' '){//non space characters
word.push_back(s[i]);
continue;
}
}
if(!word.empty())//last word
s = word+" "+res;
else
s = res;
s = s.substr(0,s.size()-1);
}

本文介绍了一种将输入字符串按单词反转的方法,并提供了Java和C++的实现细节。文章通过具体示例解释了如何去除多余的空格并确保单词间的单个空格间隔。
462

被折叠的 条评论
为什么被折叠?



