[LeetCode] 557.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:
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.
解题思路
这道题目可以帮我们熟悉字符串类型的基本操作。首先明确题意,就是将一个字符串里的每个单词倒置,但整个句子的单词顺序不变。那我的想法就是先找到将每个单词分割开的空格的位置,然后将每个单词提取出来单独操作,所以使用了string类型的substr()函数,可以很轻松地将单词提取出来操作,将提取出来的单词使用reverse()函数倒置,之后将每个单词和空格合并,得到新的字符串即为所求的字符串。
要注意的是最后一个单词的特殊情况,因为按我的方法,在循环中是找不到最后一个单词的,因为最后一个单词之后没有空格。所以我把最后一个单词与其他单词分开单独操作了。
实验代码
class Solution {
public:
string reverseWords(string s) {
int l = s.length(), t = 0;
string ss = "";
for (int i = 0; i < l; i++) {
if (s[i] == ' ') {
string s1 = s.substr(t, i-t);
t = i+1;
reverse(s1.begin(), s1.end());
ss += s1 + ' ';
}
}
string s2 = s.substr(t, l);
reverse(s2.begin(), s2.end());
ss += s2;
return ss;
}
};