LeetCode557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

1
2
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.


reverse

my code in cpp

注意如果right到了size的时候,要直接s.begin()+right,不然最后一个字母不会翻转的!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string reverseWords(string s) { 
int left = -1, right = 0;
while (++left<(int)s.size())
{
right = left;
//right移到单词末尾的后面
while (right<s.size() && s[right++] != ' ');
//翻转单词
if (right == s.size())
reverse(s.begin() + left, s.begin() + right);
else
reverse(s.begin() + left, s.begin() + right-1);
left = right - 1;
}
return s;
}

Two pointers

lc in cpp

1
2
3
4
5
6
7
8
9
10
11
string reverseWords(string s) {
int start = 0, end = 0, n = s.size();
while (start < n && end < n) {
while (end < n && s[end] != ' ') ++end;
for (int i = start, j = end - 1; i < j; ++i, --j) {
swap(s[i], s[j]);
}
start = ++end;
}
return s;
}

stringstream

  1. string转istringstream
  2. >> 操作符重载,一直读取到空格的字符串,作为一个string
  3. string::pop_back():从字符串移除末字符。等价于 erase(end() - 1, 1) 。若字符串为空则行为未定义。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    string reverseWords(string s) {
    string res = "", t = "";
    istringstream is(s);
    while (is >> t) {
    reverse(t.begin(), t.end());
    res += t + " ";
    }
    res.pop_back();//这里要将末尾的空格删去
    return res;
    }

总结

这题是151-Reverse-Words-in-a-String的简单版本.

  1. Reverse+STL
  2. Reverse+Two pointers
  3. stringstream
Thanks for Support.