字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
提示:
- 1 <= k < s.length <= 10000
思路
首先反转前n个字符, 再反转后n个字符, 最后将整个字符串反转即可得到结果.
或者直接使用substring方法截取再拼接.
代码实现
自定义方法:
class Solution {
public String reverseLeftWords(String s, int n) {
int length = s.length();
StringBuilder sb = new StringBuilder(s);
reverseString(sb, 0, n - 1);
reverseString(sb, n, length - 1);
reverseString(sb, 0, length - 1);
return sb.toString();
}
private void reverseString(StringBuilder s, int start, int end) {
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start, s.charAt(end));
s.setCharAt(end, temp);
start++;
end--;
}
}
}
substring:
class Solution {
public String reverseLeftWords(String s, int n) {
return s.substring(n, s.length()) + s.substring(0, n);
}
}
标签:chuan,end,58,Offer,int,start,length,字符串,sb
From: https://www.cnblogs.com/ahci316/p/17674365.html