344.反转字符串
class Solution {
public:
void reverseString(vector<char>& s) {
for (int i = 0, j = s.size() - 1; i < s.size()/2; i++, j--) {
swap(s[i],s[j]);
}
}
};
class Solution {
public:
void reverseString(vector<char>& s)
{
int left=0,right=s.size()-1;
while(left<=right)
{
char temp=s[right];
s[right]=s[left];
s[left]=temp;
left++;
right--;
}
}
};
541. 反转字符串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;
}
};
剑指Offer 05.替换空格
class Solution {
public:
string replaceSpace(string s)
{
int count=0;
int oldsize=s.size();
for(int i=0;i<s.size();i++)
{
if(s[i]==' ')
count++;
}
s.resize(s.size()+2*count);
int newsize=s.size();
for(int i=oldsize-1,j=newsize-1;i<j;i--,j--)
{
if(s[i]!=' ')
s[j]=s[i];
else
{
s[j]='0';
s[j-1]='2';
s[j-2]='%';
j-=2;
}
}
return s;
}
};
151.翻转字符串里的单词
class Solution {
public:
void reverse(string&s,int start,int end)
{
for(int i=start,j=end;i<j;i++,j--)
{
swap(s[i],s[j]);
}
}
void removerextraspaces(string&s)
{
int slow=0;
for(int i=0;i<s.size();i++)
{
if(s[i]!=' ')
{
if(slow!=0)
s[slow++]=' ';
while(i<s.size()&&s[i]!=' ')
{
s[slow++]=s[i++];
}
}
}
s.resize(slow);
}
string reverseWords(string s)
{
removerextraspaces(s);
reverse(s,0,s.size()-1);
int start=0;
for(int i=0;i<=s.size();i++)
{
if(i==s.size()||s[i]==' ')
{
reverse(s,start,i-1);
start=i+1;
}
}
return s;
}
};
剑指Offer58-II.左旋转字符串
class Solution {
public:
string reverseLeftWords(string s, int n)
{
reverse(s.begin(),s.begin()+n);
reverse(s.begin()+n,s.end());
reverse(s.begin(),s.end());
return s;
}
};