344. 反转字符串
https://leetcode.cn/problems/reverse-string/
class Solution {
public:
void reverseString(vector<char>& s) {
int size = s.size();
for(int j = size-1, i = 0; i < size/2; j--, i++)
{
swap(s[i],s[j]);
}
}
};
541. 反转字符串Ⅱ
https://leetcode.cn/problems/reverse-string-ii/
class Solution {
public:
string reverseStr(string s, int k) {
for(int i = 0; i < s.size(); i += 2*k)
{
if(i + k <= s.size())
reverse(s.begin()+i, s.begin()+i+k);
else
reverse(s.begin()+i, s.end());
}
return s;
}
};
151. 反转字符串中的单词
https://leetcode.cn/problems/reverse-words-in-a-string/submissions/489714833/
class Solution {
public:
string reverseWords(string s) {
int slow = 0;
for(int fast = 0; fast < s.size(); fast++)
{
if(s[fast]!=' ')
{
if(slow!=0) s[slow++] = ' '; // 单词间加空格
while(fast<s.size()&&s[fast]!=' ')
s[slow++] = s[fast++];
}
}
s.resize(slow);
//现在已经去掉多余空格了
//先整体反转,再每个单词反转回来
reverse(s.begin(),s.end());
auto start = s.begin();
for(int i = 0; i <= s.size(); i++)
{
if(i==s.size() || s[i] == ' ')
{
reverse(start, s.begin()+i);
start = s.begin() + i + 1;
}
}
return s;
}
};
标签:cn,string,--,随想录,fast,int,字符串,size
From: https://www.cnblogs.com/xsl-blogs/p/17911739.html