题目:如果字符串中只包含0和1,并且相邻字符不重复,那么该字符串被叫做交替字符串。例如:“1“、“10101“、“0101010101“……

题目:

如果字符串中只包含0和1,并且相邻字符不重复,那么该字符串被叫做交替字符串。例如:"1"、"10101"、"0101010101"

现在有一个字符串s,其中s中的每一个字符都是'0'或者'1',请找出字符串s中的最长交替子串的长度

代码:

public class Test {
    public static void main(String[] args) {
        // 测试数据
        String s = "1101011";
        // 开始测试
        System.out.println(getMaxNum(s));
    }

    /**
     * 获取最长交替子串的长度
     *
     * @param s 测试数据
     * @return 最长交替子串的长度
     */
    public static Integer getMaxNum(String s) {
        // 最大交替子串的长度
        int max = 0;
        // 交替子串长度
        int num = 1;
        // 第一个字符
        char ch = s.charAt(0);
        // 遍历字符串中的所有字符
        for (int i = 1; i < s.length(); i++) {
            // 判断当前字符和前一个字符是否相等
            if (s.charAt(i) == ch) {
                // 获取最大交替子串长度
                max = Math.max(max, num);
                // 初始化交替子串长度
                num = 1;
            } else {
                num++;
            }
            // 获取当前的字符,下一次if判断时候ch就变成了前一个字符
            ch = s.charAt(i);
        }
        // 防止最大交替子串出现在最后的情况
        max = Math.max(max, num);
        // 返回最长交替子串长度
        return max;
    }
}

结果:

5

拓展:

如果想获得最长交替子串的值,代码如下:

public class Test {
    public static void main(String[] args) {
        // 测试数据
        String s = "1101011";
        // 开始测试
        System.out.println(getMaxStr(s));
    }

    /**
     * 获取最长交替子串
     *
     * @param s 测试数据
     * @return 最长交替子串
     */
    public static String getMaxStr(String s) {
        // 最大交替子串的长度
        int max = 0;
        // 最长交替子串
        String maxStr = "";
        // 交替子串长度
        int num = 1;
        // 第一个字符
        char ch = s.charAt(0);
        // 遍历字符串中的所有字符
        for (int i = 1; i < s.length(); i++) {
            // 判断当前字符和前一个字符是否相等
            if (s.charAt(i) == ch) {
                // 获取最大交替子串长度
                max = Math.max(max, num);
                // 获取最长交替子串
                if (max == num) {
                    maxStr = s.substring(i - num, i);
                }
                // 初始化交替子串长度
                num = 1;
            } else {
                num++;
            }
            // 获取当前的字符,下一次if判断时候ch就变成了前一个字符
            ch = s.charAt(i);
        }
        // 防止出现 最大交替子串在最后 或者 字符串中只有一个字符 的情况
        max = Math.max(max, num);
        // 获取最长交替子串
        if (max == num) {
            maxStr = s.substring(s.length() - num);
        }
        // 返回最长交替子串
        return maxStr;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值