1221. 分割平衡字符串

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

 示例 1:

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


示例 2:

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

1.原创答案

class Solution {
public:
    int balancedStringSplit(string s) {
        int num=0;
        int res = 0;
        for (auto i : s){
            if (i == 'L'){
                num += 1;
                if (num==0){
                    res += 1;
                }
            }
            if(i == 'R'){
                num -= 1;
                if (num==0){
                    res += 1;
                }
            }
        }
        return res;
    }
};

2.题解参考

class Solution {
public:
    int balancedStringSplit(string s) {
        int cnt = 0;
        int balance = 0;
        for(int i = 0; i < s.size(); i++){
            if(s[i] == 'L') balance --;
            if(s[i] == 'R') balance ++;
            if(balance == 0) cnt ++;
        }
        return cnt;
    }
};

作者:jarvis1890
链接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/solution/fen-ge-ping-heng-zi-fu-chuan-tan-xin-suan-fa-da-da/
posted @ 2021-02-25 14:33  USTC丶ZCC  阅读(107)  评论(0编辑  收藏  举报