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
String
object represents an empty character sequence, or the first and last characters of character sequence represented by thisString
object both have codes greater than'\u0020'
(the space character), then a reference to thisString
object is returned.Otherwise, if there is no character with a code greater than
'\u0020'
in the string, then a newString
object 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 newString
object 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 is16
plus the length of the string argument.-
Parameters:
-
str
- the initial contents of the buffer.
Throws:
-
NullPointerException
- ifstr
isnull
-
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);
}