『《编程之法》读书笔记』——字符串旋转

一、问题描述

给定一个字符串,将字符串前面的若干个字符移到字符串的尾部。
如输入为“abcdef”输出为“defabc”

二、解题思路

解法一:蛮力移位
每一次将一个字符移到最后,执行n次
即第一次bcdefa,第二次cdefab

public static void shiftOne(char[] chars, int length) {
        char t = chars[0];
        for (int i = 0; i < length - 1; i++) {
            chars[i] = chars[i + 1];
        }
        chars[length - 1] = t;
    }
public static void rotate(char[] chars, int m) {
        int n = chars.length;
        while (m-- > 0) {// m代表循环的次数
            shiftOne(chars, n--);// n代表要处理字符串的长度
        }
    }

时间复杂度O(mn),空间复杂度(1)

解法二:三步反转

  1. 将字符串分成2部分,X部分(abc)需要移动,Y部分(def)不需要移动
  2. 分别将X部分和Y部分反转得到(cba)(fed)
  3. 整体反转(defabc)

    public static void ReverseString(char[] chars,int from,int to){
        while(from<to){
            char temp = chars[from];
            chars[from++] = chars[to];
            chars[to--] = temp;
        }
    }
    
    public static void LeftRotateString(char[] chars,int m,int n){
        m%=n;
        ReverseString(chars,0,m-1);
        ReverseString(chars,m,n-1);
        ReverseString(chars,0,n-1);
    }

    时间复杂度O(n),空间复杂度(1)

三、练习题

单词反转
输入“I am a student.” ,输出 “student. a am I”
解题思路

  1. 将整体反转(.tneduts a ma I)
  2. 再根据空格,将句子中的每个单词反转

假设输入为I am a student. 根据下面代码可以总结出循环语句

        int pre = -1;
        int next = -1;
        pre = next;
        next = 8;
        ReverseString(chars, pre+1, next-1);
        pre = next;
        next = 10;
        ReverseString(chars, pre+1, next-1);
        pre = next;
        next = 13;
        ReverseString(chars, pre+1,next-1);
        pre = next;
        next = n+1;
        ReverseString(chars, pre+1,next-1);

代码

public static void RatoteString(char[] chars,int n){
        //整体反转
        ReverseString(chars, 0, chars.length-1);
        int pre = -1;
        int next = -1;
        //反转单词
        for(int i = 0;i<=n;i++){
            if(chars[i]==' '||i==n){
                if(i==n){
                    i = n+1;
                }
                pre = next;
                next = i;
                ReverseString(chars, pre+1, next-1);
            }
        }
    }
    public static void ReverseString(char[] chars,int from,int to){
        while(from<to){
            char temp = chars[from];
            chars[from++] = chars[to];
            chars[to--] = temp;
        }
    }

测试

String str = "I am a very very   good student.";

输出

student. good   very very a am I
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值