您的位置:首页 > 其它

Leetcode-Reverse Words in a String

2018-01-22 20:38 225 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

void reverseWords(string &s) {
int pos = 0;
string res;
for (int i = 0; i != s.size(); i++) {
if (s[i] == ' ') {
if (i > pos) { //a word
res = s.substr(pos, i - pos) + " " + res;
}
pos = i + 1;//next word
}
else if (i == s.size() - 1) {//last word size=1
res = s.substr(pos, s.size() - pos) + " " + res;
}

}
s = res.substr(0, res.size()-1);
}
notes:

1. substr(pos,len)

2. 字符串中连续的多个空格被当作一个空格

    pos每次指向一个单词的第一个字符,如果i==pos说明字符串开头有空格,pos=i+1就能跳过开头的空格

3.字符串最后一个单词可能没有空格,需要单独处理

4.思想类似于“头插法”

   每次取一个单词,然后将上一次得到的子串连在新单词后面,就实现了单词顺序反转。

参考a solution from Leetcode:https://discuss.leetcode.com/topic/3087/accepted-simple-cpp-code-in-just-a-few-lines
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: