当前位置 博文首页 > 是琳琳呀!的博客:字符串的左旋转java
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = “abcdefg”, k = 2
输出: “cdefgab”
示例 2:
输入: s = “lrloseumgh”, k = 6
输出: “umghlrlose”
class Solution {
public String reverseLeftWords(String s, int n) {
char[] a=s.toCharArray();
int len=a.length;
if(a==null||n<0||n>len){
return null;
}
res(a,0,n-1);
res(a,n,len-1);
res(a,0,len-1);
return new String(a);
}
void res(char[] c,int s,int e){
while(s <= e){
char tmp = c[s];
c[s] = c[e];
c[e] = tmp;
s++;
e--;
}
}
}
cs