反转字符串I
简单的双指针
class Solution {
public:
void reverseString(vector<char>& s) {
int begin = 0;
int end = s.size() - 1;
while(begin < end)
{
swap(s[begin], s[end]);
begin++;
end--;
}
}
};
反转字符串II
注意i最后的位置即可:i+2*k < s.size()
class Solution {
public:
string reverseStr(string s, int k) {
int i = 0;
//1.错误for(; i < s.size(); i += 2*k)
for(; i+2*k < s.size(); i += 2*k)
{
reverse(s.begin() + i, s.begin() + i + k);
}
if(s.size() - i >= k)
{
reverse(s.begin() + i, s.begin() + i + k);
}
else
{
reverse(s.begin() + i, s.begin() + s.size());
}
return s;
}
};
反转字符串III反转字符中的单词
class Solution {
public:
string reverseWords(string s) {
int i = 0;
while(i < s.size())
{
int start = i;
while(i < s.size() && s[i] != ' ')
{
i++;
}
int left = start;
int right = i;
reverse(s.begin() + left, s.begin() + right);
while(s[i] == ' ')
i++;
}
return s;
}
};