【leetcode_easy】557. Reverse Words in a String III

时间:2023-03-09 03:48:20
【leetcode_easy】557. Reverse Words in a String III

problem

557. Reverse Words in a String III

solution1:字符流处理类istringstream.

class Solution {
public:
string reverseWords(string s) {
string ans = "", t = "";
istringstream is(s);//
while(is >> t)
{
reverse(t.begin(), t.end());
ans += t + " ";//err.
}
ans.pop_back();
return ans;
}
};

solution2:单词首尾指针。

class Solution {
public:
string reverseWords(string s) {
int start = , end = ;
while(start<s.size() && end<s.size())
{
while(end < s.size() && s[end]!=' ') end++;
for(int i=start, j=end-; i<j; i++, j--)//
{
swap(s[i], s[j]);//
}
start = ++end;
//start = end + 1;
//end++;
}
return s;
}
};

参考

1. Leetcode_easy_557. Reverse Words in a String III;

2. Grandyang;