zoukankan      html  css  js  c++  java
  • 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/
  • 相关阅读:
    iOS 图片加载
    viewController 生命周期 转
    @import和@class的区别
    git 使用总结
    iOS开发 关于property的简单总结
    Swift-6-函数
    Swift-5-流程控制
    Swift-4-数组和字典
    Swift-3-字符串和字符
    Swift-2-基本操作符
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/14446793.html
Copyright © 2011-2022 走看看