反转字符串 https://leetcode-cn.com/problems/reverse-string/
class Solution {
public:
void swap(char& a,char& b)
{
char temp=a;
a=b;
b=temp;
}
void reverseString(vector<char>& s) {
if(s.size()==1) return;
for(int i=0,j=s.size()-1;i<=(s.size()-2)/2;i++,j--)
{
swap(s[i],s[j]);
}
}
};
反转字符串II https://leetcode-cn.com/problems/reverse-string-ii/
class Solution {
public:
void swap(char& a,char& b)
{
char temp=a;
a=b;
b=temp;
}
string reverseStr(string s, int k) {
int index=-1;
while(index+2*k<=s.size()-1)
{
index+=2*k;
for(int i=index-2*k+1,j=index-k;i<j; i++,j--)
{
swap(s[i],s[j]);
}
}
int len=s.size()-1-index;
if(len<k)
{
for(int i=index+1,j=s.size()-1;i<j;i++,j--)
{
swap(s[i],s[j]);
}
}
else if(len>=k&&len<2*k)
{
for(int i=index+1,j=index+k;i<j;i++,j--)
{
swap(s[i],s[j]);
}
}
return s;
}
};
翻转字符串里的单词 https://leetcode-cn.com/problems/reverse-words-in-a-string/
class Solution {
public:
void trim(string& s)
{
if(s.size()==1) return;
int slow=0,fast=0;
while(s[fast]==' ')
{
fast++;
}
while(fast<=s.size()-1)
{
if(s[fast]==' '&&s[fast-1]==' ')
{
fast++;
}
else
{
s[slow++]=s[fast++];
}
}
if(s[slow-1]==' ') s.resize(slow-1);
else
{
s.resize(slow);
}
}
void swap(char& a,char& b)
{
char temp=a;
a=b;
b=temp;
}
string reverseWords(string s) {
trim(s);
for(int i=0,j=s.size()-1;i<j;i++,j--)
{
swap(s[i],s[j]);
}
int pre=0,cur=0;
while(cur<=s.size()-1)
{
cur++;
if(s[cur]==' '||cur==s.size())
{
for(int i=pre,j=cur-1;i<j;i++,j--)
{
swap(s[i],s[j]);
}
pre=cur+1;
}
}
return s;
}
};
C++ string resize(int x),设置string的大小为x,舍去后面多余的字符
左旋转字符串 https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
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;
}
};
|