JZ43-左旋转字符串

左旋转字符串

https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

/**
 *   abc   cba
 * XYZdef  fedZYX  相加 cbafedZYX 再反转 XYZdefabc
 */
class Solution2 {
    public String LeftRotateString(String str, int n) {
        if (str == null || str.length() == 0) {
            return str;
        }
        char[] chars = str.toCharArray();
        int realN = n % chars.length;

        reverse(chars, 0, realN - 1);
        reverse(chars, realN, chars.length - 1);
        reverse(chars, 0, chars.length - 1);

        return new String(chars);
    }

    private void reverse(char[] chars, int start, int end) {
        while (start < end) {
            swap(chars, start, end);
            start++;
            end--;
        }
    }

    private void swap(char[] chars, int i, int j) {
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}

全部评论

相关推荐

牛马人的牛马人生:一开始看成了网吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务