[LeetCode]1221. 分割平衡字符串

分割字符串

Posted by JinFei on September 7, 2021

题目描述

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

Example 1:

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

Example 2:

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

Example 3:

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

Constraints:

  • 1 <= s.length <= 1000
  • s[i] = ‘L’ 或 ‘R’
  • s 是一个 平衡 字符串

解题思路

  • 贪心搜索
  • 设置个计数器,遍历整个字符串,当发现是’L’时,count进行累加,否则,累减。当如果计数器为0时,则说明是一个平衡字符子串。

C++代码

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