剑指 Offer 58 - II(Java)-左旋转字符串(简单)

题目:

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

 

示例 1:

输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:

输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
 

限制:

1 <= k < s.length <= 10000

来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

参考:代码随想录文字版讲解

拿例1举例:s = "abcdefg", k = 2 输出: "cdefgab"

①先翻转字符串s的前k个字符串,[0, k -1]

b a c d e f g

②再翻转后s.length-k个字符串,[k, s.length() - 1]

b a g f e d c

③最后翻转整个字符串,[0, s.length() - 1]

c d e f g a b

代码:

 1 class Solution {
 2     public String reverseLeftWords(String s, int n) {
 3         char[] ch = s.toCharArray();
 4         reverse(ch, 0, n - 1);
 5         reverse(ch, n, s.length() - 1);
 6         reverse(ch, 0, s.length() - 1);
 7         return new String(ch);
 8     }
 9     public void reverse(char[] ch, int start, int end){
10         while (start < end){
11             char temp = ch[end];
12             ch[end] = ch[start];
13             ch[start] = temp;
14             start++;
15             end--;
16         } 
17     }
18 }
posted on 2023-05-16 09:52  我不想一直当菜鸟  阅读(11)  评论(0编辑  收藏  举报