Reverse Words in a String
:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Clarification:
实现代码:
- 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.
class Solution {
public:
void reverseWords(string &s) {
string res = "";
if(s.length()==0) return;
int i=s.length()-1,end=i, start=i;
while(i>=0){
if(s[i--]!=' ') {
start=i+1;
if((i>=0 && s[i]==' ')||i<0) {
res+=s.substr(start,end-start+1)+" ";
end = start-1;
}
}
else end--;
}
s=res.substr(0,res.length()-1);
}
};
或者利用java的spilt函数:
class Solution {
public:
void reverseWords(string &s) {
string res = "";
if(s.length()==0) return;
int i=s.length()-1,end=i, start=i;
while(i>=0){
if(s[i--]!=' ') {
start=i+1;
if((i>=0 && s[i]==' ')||i<0) {
res+=s.substr(start,end-start+1)+" ";
end = start-1;
}
}
else end--;
}
s=res.substr(0,res.length()-1);
}
};
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] array = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = array.length - 1; i >= 0; --i) {
if (!array[i].equals("")) {
sb.append(array[i]).append(" ");
}
}
//remove the last " "
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}
public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
String[] array = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = array.length - 1; i >= 0; --i) {
if (!array[i].equals("")) {
sb.append(array[i]).append(" ");
}
}
//remove the last " "
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}