剑指OFFER 左旋转字符串
方法1:新创建一个字符串
class Solution {
public:
string LeftRotateString(string str, int n) {
string res;
int len = str.size();
for(int i=n;i<len+n;i++)
{
res.push_back(str[i%len]);
}
return res;
}
};
写得十分简洁了,比当时第一次写这种类型的题的时候进步很大了.
方法2:直接在原字符串上进行修改
稍加修改就可以通过了
class Solution {
public:
void rotateStr(string &str,int left,int right)
{
while (left < right)
{
char tc = str[left];
str[left] = str[right];
str[right] = tc;
left++;
right--;
}
}
string LeftRotateString(string str, int n) {
int len = str.length();
if(len==0)return string("");
int new_offset = len - n;
rotateStr(str, 0, len-new_offset-1);
rotateStr(str, len-new_offset, len-1);
rotateStr(str, 0, len-1);
return str;
}
};