您的位置:首页 > 其它

[leetcode]151. Reverse Words in a String

2017-05-26 11:45 405 查看
题目链接:https://leetcode.com/problems/reverse-words-in-a-string/#/description

Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

class Solution {
public:

// function to reverse any part of string from i to j (just one word or entire string)
void reverseword(string &s, int i, int j){
while(i<j){
char t=s[i];
s[i++]=s[j];
s[j--]=t;
}
}

void reverseWords(string &s) {

int i=0, j=0;
int l=0;
int len=s.length();
int wordcount=0;

while(true){
while(i<len && s[i] == ' ') i++; // skip spaces in front of the word
if(i==len) break;
if(wordcount) s[j++]=' ';
l=j;
while(i<len && s[i] != ' ') {s[j++]=s[i++];}
reverseword(s,l,j-1); // reverse word in place
wordcount++;

}

s.resize(j); // resize result string
reverseword(s,0,j-1); // reverse whole string
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: