[剑指 Offer 58 - II. 左旋转字符串] Java实现

原文链接: https://kdocs.cn/l/cr0eXiEQ2gyS?linkname=StGvdyTWe9

题目地址:https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/

[剑指 Offer 58 - II. 左旋转字符串] Java实现

✅题目

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

示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"

思路:

先利用 StringBuilder 读字符串的后几位,读完后再把字符串的前几位append()进去。

题解:

class Solution {
    public String reverseLeftWords(String s, int n) {
        StringBuilder sb = new StringBuilder(s.length());
        for(int j = n; j < s.length(); j++) {
            sb.append(s.charAt(j));
        }
        for(int i = 0; i < n; i++){
          sb.append(s.charAt(i));
      }
      String res =sb.toString();
        return res;
    }
}

测试代码(可以自己在IDE上测试输出一下)

package test01;

public class test {
    public static void main(String[] args) {
        String s = "lrloseumgh";
//        String s = "abcdef";
    int n = 6;
    int l = s.length();//6
    StringBuilder sb1 = new StringBuilder();
    int m = l - n;//3
        for(int j = n; j < l; j++) {
        
        sb1.append(s.charAt(j));
    }
    
    for(int i = 0; i < n; i++){
      sb1.append(s.charAt(i));
  	}
    String res =sb1.toString();//注意这里引用变量sb

    System.out.print(res);

	}
}

posted @ 2022-06-20 20:48  王嘚嘚  阅读(24)  评论(1)    收藏  举报