【Leetcode刷题日记】1869.哪种连续子字符串更长

题目

一开始的时候的想法已经蛮不错,设立两个指针,一个在前一个在后,如果前后相同,再判断相同的是哪一个字符,长度++。最后再求最长。。。代码太稚嫩了,一点都不像是一个研究生能写出的代码。

 自己原始代码

class Solution {
    public static boolean checkZeroOnes(String s) {
        int count1 = 1;
        int tmp0=1;
        int tmp1=1;
        int count0 = 1;
        int p = 1; //前面的指针
        int t = 0; //后面的指针
        if(s.length()==1) return(s.charAt(0)=='1'); //长度为1的情况
        for(;p<s.length();p++,t++){
            if(s.charAt(p)==s.charAt(t)){
                if(s.charAt(p)=='0') tmp0++; //0串长度
                else tmp1++;    //1串长度
                }
            else{
                switch (s.charAt(p)){
                    case '0': tmp0= 1; break; //恢复为1
                    case '1': tmp1 = 1; break;
                }
            }
            if (tmp0 >count0) count0 = tmp0;
            if (tmp1 > count1) count1 = tmp1;    //求最大
        }
        return count1 > count0;

    }
}

修改后的代码

使用了max函数,且判断方法更简洁。比较大小的Boolean型return原来可以有简洁的写法。

class Solution {
    public static boolean checkZeroOnes(String s) {
        int len1 = 0; int max1 =0;
        int len0 =0; int max0 = 0;
        for(int i =0;i<s.length();i++){
            if(s.charAt(i)=='1') {
                len1++;
                len0 = 0;
            }
            else {
                len0++;
                len1 = 0;
            }
            max0 = Math.max(len0,max0);
            max1 = Math.max(len1,max1);
        }
    return max1>max0;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值