版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38088298/article/details/85344697
- 描述: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:
Input: “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
- 分析:给出一个string对其中每一个单词进行反转,输出所得反转单词拼接成的string。由题中描述可以知道,除最后一个单词以外,每个单词都可以通过检测单词后的空格提取出。
- 思路一:给原string后补一个空格,用来检测空格,之后使用find (const char* s, size_t pos = 0)函数用来找到第i个元素之后的空格,截取字串进行反转,最后拼接到新string中。
class Solution {
public:
string reverseWords(string s) {
int pos;
string res;
s += ' ';
for (int i = 0; i < s.size(); i++) {
pos = s.find(' ', i);
string temp = s.substr(i, pos - i);
reverse(temp.begin(), temp.end());
res += temp + ' ';
i = pos;
}
res.erase(--res.end());
return res;
}
};