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 |
Input: "Let's take LeetCode contest" |
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
my code in cpp
注意如果right到了size的时候,要直接s.begin()+right,不然最后一个字母不会翻转的!
1 |
string (string s) { |
Two pointers
lc in cpp
1 |
string (string s) { |
stringstream
- string转istringstream
- >> 操作符重载,一直读取到空格的字符串,作为一个string
- string::pop_back():从字符串移除末字符。等价于 erase(end() - 1, 1) 。若字符串为空则行为未定义。
1
2
3
4
5
6
7
8
9
10string (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的简单版本.
- Reverse+STL
- Reverse+Two pointers
- stringstream
近期评论