剑指Offer 58 - II. 左旋转字符串


双指针

class Solution {
    public String reverseLeftWords(String s, int n) {

        StringBuilder str = new StringBuilder(s);

        /**
         * 分别反转前n个字符和剩余字符,然后反转全部字符
         */
        reverse(str, 0, n - 1);
        reverse(str, n, str.length());
        reverse(str, 0, str.length());

        return str.toString();
    }

    /**
     * 定义反转字符串方法
     */
    public void reverse(StringBuilder str, int left, int right){

        while (left < right){

            char temp;
            temp = str.charAt(left);

            /**
             * setCharAt()方法修改StringBuilder对象值
             */
            str.setCharAt(left, str.charAt(right));
            str.setCharAt(right, temp);
            left++;
            right--;
        }
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

库函数

class Solution {
    public String reverseLeftWords(String s, int n) {

        return s.substring(n) + s.substring(0, n);
    }
}

https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/