[编程题]左旋转字符串
• 热度指数：275178 时间限制：C/C++ 1秒，其他语言2秒 空间限制：C/C++ 32M，其他语言64M
• 算法知识视频讲解

```class Solution {
public:
string LeftRotateString(string str, int n)
{
int len = str.size();
if(len == 0) return str;
n %= len;
for(int i = 0, j = n - 1; i < j; ++i, --j) swap(str[i], str[j]);
for(int i = n, j = len - 1; i < j; ++i, --j) swap(str[i], str[j]);
for(int i = 0, j = len - 1; i < j; ++i, --j) swap(str[i], str[j]);
return str;
}
};```

```class Solution {
public:
string LeftRotateString(string str, int n) {
int len = str.length();
if(len == 0) return "";
n = n % len;
str += str;
return str.substr(n, len);
}
};
```

```//按照剑指offer书上的方法，两次翻转字符串。
class Solution {
public:
string LeftRotateString(string str, int n) {
reverse(str.begin(), str.end());
reverse(str.begin(), str.begin() + str.size() - n);
reverse(str.begin() + str.size() - n, str.end());
return str;
}
};```

```
/*

无力吐槽你们的做法了，这种AC，你们觉得面试能过吗？这道题考的核心是应聘者是不是可以灵活利用字符串翻转。假设字符串abcdef，n=3，设X=abc，Y=def，所以字符串可以表示成XY，如题干，问如何求得YX。假设X的翻转为XT，XT=cba，同理YT=fed，那么YX=(XTYT)T，三次翻转后可得结果。

*/

class Solution {
public:
void fun(string &s,int start,int end)
{
char temp;
while(start<end)
{
temp=s[start];
s[start]=s[end];
s[end]=temp;
start++;
end--;
}
}
string LeftRotateString(string str, int n) {
int len=str.length();
if(0==len || 0==n)
return str;
string &temp=str;
fun(temp,0,n-1);
fun(temp,n,len-1);
fun(temp,0,len-1);
return str;
}
};

```

```public class Solution {
public String LeftRotateString(String str,int n) {
char[] chars = str.toCharArray();
if(chars.length < n) return "";
reverse(chars, 0, n-1);
reverse(chars, n, chars.length-1);
reverse(chars, 0, chars.length-1);
StringBuilder sb = new StringBuilder(chars.length);
for(char c:chars){
sb.append(c);
}
return sb.toString();
}

public void reverse(char[] chars,int low,int high){
char temp;
while(low<high){
temp = chars[low];
chars[low] = chars[high];
chars[high] = temp;
low++;
high--;
}
}
}

```

# python solution:

``````# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
return s[n:]+s[:n]
``````

```public class Solution {
public String LeftRotateString(String str,int n) {
//保证旋转的位数大于字符串的长度，否则返回空字符串
if(n>str.length())
return "";
//把原字符串截取成俩字符串，然后拼接
String s1 = str.substring(0, n);
String s2 = str.substring(n,str.length());
return s2 + s1;
}
}```

public class Solution {
public String LeftRotateString(String str,int n) {
int length = str.length();
if(length<=0){
return "";
}
StringBuffer sb = new StringBuffer(str.substring(0, n));
StringBuffer sb1 = new StringBuffer(str.substring(n, str.length()));
sb1.append(sb);
//System.out.println(sb1);
return sb1.toString();

}
}

``````/**
* 题目描述
* 汇编语言中有一种移位指令叫做循环左移（ROL），现在有个简单的任务，
* 就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S，
* 请你把其循环左移K位后的序列输出。例如，字符序列S=”abcXYZdef”,
* 要求输出循环左移3位后的结果，即“XYZdefabc”。
* 是不是很简单？OK，搞定它！
*
* @author shijiacheng
*/
public class LeftRotateStringSolution {
public String LeftRotateString(String str, int n) {
char[] chars = str.toCharArray();
if (chars.length < n) {
return "";
}
reverse(chars, 0, n - 1);
reverse(chars, n, chars.length - 1);
reverse(chars, 0, chars.length - 1);

return new String(chars);
}

public void reverse(char[] chars, int start, int end) {
while (start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
}
``````

```//C++
/*解法一：在原字符串上修改
“abcdef”循环左移9位（3位）

“cbafed”-> “defabc”
*/
class Solution {
public:
string LeftRotateString(string str, int n) {
int len = str.size();
if(len <= 0)
return "";
n = n%len;
if(n==0)
return str;
reverseStr(str,0,n-1);
reverseStr(str,n,len-1);
reverseStr(str,0,len-1);
return str;
}
void reverseStr(string &str, int left, int right)
{
for(int i=left,r=right;i<=left+(right-left)/2;++i){
swap(str[i],str[r--]);
}
}
};
/*解法二：

*/class Solution {

public:

string LeftRotateString(string str, intn) {

string ret;

intlen = str.size();

if(len <= 0)

return"";

n = n%len;

ret = str+str.substr(0,n);

ret = ret.substr(n,str.size());

returnret;

}

};

```

```class Solution {
public:
string LeftRotateString(string str, int n) {
string l,r;
for(int i=0;i<n;i++) r+=str[i];
for(int i=n;i<str.size();i++) l+=str[i];
return l+r;
}
};```

BA = (A.reverse() B.reverse()).reverse(), 模拟这三个字符串翻转操作即可
```# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
res, length = list(s), len(s)
if n > length : return ""
for i in range(int(n/2)):
res[i], res[n-1-i] = res[n-1-i], res[i]
for i in range(n, int((n+length)/2)):
res[i], res[length-1-i+n] = res[length-1-i+n], res[i]
for i in range(int(length/2)):
res[i], res[length-1-i] = res[length-1-i], res[i]
return "".join(res)
```

``````package String;

/**
* 左旋转字符串
* 汇编语言中有一种移位指令叫做循环左移（ROL），现在有个简单的任务，就是用字符串模拟这个指令的运算结果。
* 对于一个给定的字符序列S，请你把其循环左移K位后的序列输出。
* 例如，字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果，即“XYZdefabc”。是不是很简单？OK，搞定它！
*/
public class Solution31 {
public static void main(String[] args) {
Solution31 solution31 = new Solution31();
String str = "abcXYZdef";
System.out.println(solution31.LeftRotateString(str, 3));
}

public String LeftRotateString(String str, int n) {
if (str == null || str.length() == 0) return "";
StringBuilder sb1 = new StringBuilder(str.substring(0, n));
StringBuilder sb2 = new StringBuilder(str.substring(n, str.length()));
sb2.append(sb1);
return sb2.toString();
}
}
``````

```public class Solution {
/**
* 思路：
* 1.先翻转前半部分
* 2.再翻转后半部分
* 3.再对字符串整个进行翻转
*
* 考点：不使用库对字符串进行灵活的翻转
*/
public String LeftRotateString(String str,int n) {
if (str == null || str.length() == 0 || n < 0 || n > str.length()) {
return str;
}
char[] ch = str.toCharArray();
reverseString(ch, 0, n - 1);
reverseString(ch, n, str.length() - 1);
reverseString(ch, 0, str.length() - 1);
return new String(ch);
}

/**
* 对字符数组 ch 的 start 到 end 范围内的字符进行翻转
*/
public void reverseString(char[] ch, int start, int end) {
while (start < end) {
char temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
start++;
end--;
}
}

}
```

```class Solution {
public:
string LeftRotateString(string str, int n) {
int len=str.length();
if(len<=0||n<=0)
return str;       //假设输入str为abcXYZdef，n=3
Reverse(str,0,n-1);   //反转前n个字符，得到cbaXYZdef
Reverse(str,n,len-1); //反转第n个字符后面所有的字符cbafedZYX
Reverse(str,0,len-1); //反转整个字符串XYZdefabc
return str;
}
void Reverse(string &str,int begin,int end)
{
int temp;
while(begin<end)
{
temp=str[begin];
str[begin]=str[end];
str[end]=temp;

begin++,end--;
}
}
};```

```    public static String LeftRotateString(String str,int n) {
if (str == null || str.length() == 0) {
return str;
}

n = n % str.length();
return str.substring(n, str.length()) + str.substring(0, n);
}```

``` char *LeftRotateString(char *str, int n) {

char *tmp;

tmp = (char *)malloc((n + 1)*sizeof(char));
if (!tmp)
{
/* code */
printf("allocate memory failed!.\n");
exit(1);
}

memcpy(tmp, str, n);
*(tmp + n) = '\0';

memcpy(str, str + n, strlen(str) - n);
*(str + strlen(str) - n) = '\0';

strcat(str, tmp);
free(tmp);

return str;
}```

```class Solution:
def LeftRotateString(self, s, n):
return s[n:len(s)]+s[0:n]
python一句话搞定```

```class Solution:
def LeftRotateString(self, s, n):
# write code here
res = []
tmp = []
c = ['']*len(s)
i = 0
if n >=len(s):return s
for j in s:
c[i]=j
i+=1
for _ in range(n):
a = c.pop(0)
tmp.append(a)
for k in c:
res.append(k)
for f in tmp:
res.append(f)
return ''.join(res)
print(Solution().LeftRotateString('abcXYZdef', 4))```

```public class Solution {
public String LeftRotateString(String str,int n) {
if(str.equals("")) return "";
n %= str.length(); // 处理循环移
str = str + str; // 复制str,则原str左移n就相当于str的第一个字符右移n
return str.substring(n,n + str.length() / 2);
}
}

```

1209条回答 83336浏览

# 通过挑战的用户

• 2020-01-21 02:10:23
• 2020-01-21 01:04:42
• 2020-01-21 00:15:34
• 2020-01-20 23:12:42
• 2020-01-20 22:44:31

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题