leetcode-1221. 分割平衡字符串

    //    1221. 分割平衡字符串
//    在一个「平衡字符串」中,'L' 和 'R' 字符的数量是相同的。
//    给出一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
//    返回可以通过分割得到的平衡字符串的最大数量。
//    示例 1:
//    输入:s = "RLRRLLRLRL"
//    输出:4
//    解释:s 可以分割为 "RL", "RRLL", "RL", "RL", 每个子字符串中都包含相同数量的 'L' 和 'R'。
//    来源:力扣(LeetCode)
//    链接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings

    //考虑s也是一个平衡字符串
    //这种做法不全面,但是能通过
    public int balancedStringSplit(String s) {
        int t = 0;
        int count = 0;
        char[] c = s.toCharArray();
        for (char c1 : c) {
            if (c1 == 'R') t++;
            if (c1 == 'L') t--;
            if (t == 0) count++;
        }
        return count;
    }
    //第二种做法--测试报错
    public int balancedStringSplit2(String s) {
        if (s.charAt(0) == 'R') return stringFind(s, "RL");
        else return stringFind(s, "LR");
    }

    public int stringFind(String fa, String son) {
        int number = 0;
        int i = 0;
        while (i != -1) {
            int a = fa.indexOf(son);
            int b = fa.indexOf(changeson(son));
            if ((a != -1 && a < b) || (a != -1 && b == -1)) {
                number++;
                fa = fa.substring(a + 2);
            }
            if ((b != -1 && b < a) || (b != -1 && a == -1)) {
                number++;
                fa = fa.substring(b + 2);
            }
            if (a == -1 && b == -1) i = -1;
        }
        return number;
    }

    public String changeson(String son) {
        if (son.equals("RL")) return "LR";
        else return "RL";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值