题解 | #左旋转字符串#超简单的字符串拼接

左旋转字符串

https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param str string字符串
     * @param n int整型
     * @return string字符串
     */
    public String LeftRotateString (String str, int n) {
        if (str == null || str.length() == 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder(str);
        // 当n==0时停止遍历,此时字符串已经得到我们想要的值
        while (n > 0) {
            n--;
            String temp = sb.toString();
            //实际上每次变化的只是把开头的第一个字符移到字符串的最后一个位置,其他字符向前移动而已
            //利用现成的string api即可完成
            sb = new StringBuilder(temp.substring(1) + temp.charAt(0));
        }
        return sb.toString();
    }
}

全部评论

相关推荐

牛马43373018...:这人真懂什么叫熵吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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