剑指offer(43)左旋转字符串

/*使用内置函数,用三个reverse(),先分别反转前k,再反转后面的,再整体翻转
public class Solution {
    public String LeftRotateString(String str,int n) {
        if(str == null || str.length() == 0 || n <= 0){
            return str;
        }
        int length = str.length();
        String strPart1 = str.substring(0, n);
        String strPart2 = str.substring(n, length);
        String reStrPart1 = new StringBuffer(strPart1).reverse().toString();
        String reStrPart2 = new StringBuffer(strPart2).reverse().toString();
        String temp = reStrPart1 + reStrPart2;
        String res = new StringBuffer(temp).reverse().toString();
        return res;
    }
}
*/
public class Solution{//首尾互换,逐步往里
    public String LeftRotateString(String str, int n){
     if(str == null || str.length()== 0 || n <= 0 || n > str.length()){
         return str;
     }   
        char[] chs = str.toCharArray();
        int length = chs.length;
        reverse(chs, 0, n - 1);
        reverse(chs, n, length - 1);
        reverse(chs, 0, length - 1);
       // return chs.toString();不可以,因为数组本身输出就不是一个一个的元素,而是地址表示
        return new String(chs);
    }
    public void reverse(char[] chs, int start, int end){
        char temp;
        while(start < end){
            temp = chs[end];
            chs[end] = chs[start];
            chs[start] = temp;
            start++;
            end--;
        }
    }
}

全部评论

相关推荐

06-07 21:26
江南大学 C++
话不多说,直接上时间线和图片1.2024年10月底发offer,并签三方2.2025年5月底公司违约
从零开始的转码生活:希望所有签了三方但直接违约的公司都倒闭!都倒闭!都倒闭!
点赞 评论 收藏
分享
哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
昨天 16:23
已编辑
长安大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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