分割平衡字符串

作者: xialu | 来源:发表于2021-09-07 08:24 被阅读0次

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings

    题目描述:

    在一个 平衡字符串 中,'L' 和 'R' 字符的数量是相同的。
    给你一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。
    注意:分割得到的每个字符串都必须是平衡字符串。
    返回可以通过分割得到的平衡字符串的 最大数量 。

    示例 1:

    输入:s = "RLRRLLRLRL"
    输出:4
    解释:s 可以分割为 "RL"、"RRLL"、"RL"、"RL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。

    示例 2:

    输入:s = "RLLLLRRRLR"
    输出:3
    解释:s 可以分割为 "RL"、"LLLRRR"、"LR" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。

    示例 3:

    输入:s = "LLLLRRRR"
    输出:1
    解释:s 只能保持原样 "LLLLRRRR".

    示例 4:

    输入:s = "RLRRRLLRLL"
    输出:2
    解释:s 可以分割为 "RL"、"RRRLLRLL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。

    题目分析:
    1. 分割为最大平衡字符串
    2. 平衡字符串中'L','R'数量相同且连续
    思路:

    初始化计数器count=0,遍历字符串,记录R,L的数量,遇到R,count + 1,遇到L,count - 1,每次count等于0时,代表找到了一个最大平衡字符串,结果数量+1.

    代码实现:
    class Solution {
        public int result = 0;
        public char r = 'R';
        public char l = 'L';
        public int balancedStringSplit(String s) {
            int count =  0;
            int len = s.length();
            for (int i = 0; i < len; i++) {
                if (s.charAt(i) == r) count++;
                if (s.charAt(i) == l) count--;
                if (count == 0) result++; // 找到了一个最大平衡子字符串。
            }
            return result;
        }
    }
    

    相关文章

      网友评论

        本文标题:分割平衡字符串

        本文链接:https://www.haomeiwen.com/subject/lseuwltx.html