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"
Note:In the string, each word is separated by single space and there will not be any extra space in the string.
题目的要求很简单,要求翻转每个单词,但是保持空格以及单词的相对顺序不变,最开始我想的是用一个栈,遇见空格把栈中的单词弹出,最后也确实AC了,代码如下:
1 class Solution {
2 public:
3 string reverseWords(string s) {
4 stack<char> sta;
5 //s += ' ';
6 string res = "";
7 for (int i = 0; i <= s.length(); i++)
8 {
9 if (s[i] != ' ' && i != (s.length()))
10 //if (s[i] != ' ')
11 {
12 sta.push(s[i]);
13 //cout<<sta.top()<<endl;
14 }
15 else
16 {
17 while (!sta.empty())
18 {
19 res += sta.top();
20 //std::cout<<sta.top();
21 sta.pop();
22 }
23 if (s[i] == ' ')
24 res += ' ';
25 }
26 }
27 cout<<endl;
28 return res;
29 }
30 };当然也可以使用reverse函数,代码如下:
class Solution {
public:
string reverseWords(string s) {
int front = ;
for (int i = ; i <= s.length(); i++)
{
if (s[i] == ' ' || i == s.length())
{
reverse(&s[front], &s[i]);
front = i + ;
}
}
return s;
}
};或者是使用两个指针,分别指向字符串的 头和尾部:
1 class Solution {
2 public:
3 string reverseWords(string s) {
4 int start = 0, end = 0, n = s.size();
5 while (start < n && end < n) {
6 while (end < n && s[end] != ' ') ++end;
7 for (int i = start, j = end - 1; i < j; ++i, --j) {
8 swap(s[i], s[j]);
9 }
10 start = ++end;
11 }
12 return s;
13 }
14 };