LeetCode //C - 1221. Split a String in Balanced Strings

1221. Split a String in Balanced Strings

Balanced strings are those that have an equal quantity of 'L' and 'R' characters.

Given a balanced string s, split it into some number of substrings such that:

  • Each substring is balanced.

Return the maximum number of balanced strings you can obtain.

Example 1:

Input: s = "RLRRLLRLRL"

Output: 4

Explanation: s can be split into "RL", "RRLL", "RL", "RL", each substring contains same number of 'L' and 'R'.

Example 2:

Input: s = "RLRRRLLRLL"

Output: 2

Explanation: s can be split into "RL", "RRRLLRLL", each substring contains same number of 'L' and 'R'.

Note that s cannot be split into "RL", "RR", "RL", "LR", "LL", because the 2nd and 5th substrings are not balanced.

Example 3:

Input: s = "LLLLRRRR"

Output: 1

Explanation: s can be split into "LLLLRRRR".

Constraints:
  • 2 <= s.length <= 1000
  • si is either 'L' or 'R'.
  • s is a balanced string.

From: LeetCode

Link: 1221. Split a String in Balanced Strings


Solution:

Ideas:

use a counter. Add +1 for R, -1 for L. Every time counter becomes 0, we found one balanced substring.

Code:
c 复制代码
int balancedStringSplit(char* s) {
    int balance = 0;
    int count = 0;

    for (int i = 0; s[i] != '\0'; i++) {
        if (s[i] == 'R') {
            balance++;
        } else {
            balance--;
        }

        if (balance == 0) {
            count++;
        }
    }

    return count;
}
相关推荐
漂流瓶jz42 分钟前
UVA-1442 洞穴 题解答案代码 算法竞赛入门经典第二版
c++·算法·题解·aoapc·算法竞赛入门经典·uva
圣保罗的大教堂42 分钟前
leetcode 835. 图像重叠 中等
leetcode
叠层归一研究院2 小时前
基于极限自指的叠层归一宇宙结构理论——无元外部封闭系统的内生区分模型
人工智能·经验分享·算法·agi
Selvaggia3 小时前
Diffusion Model 的基本原理与模型架构
算法
wabs6664 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin034 小时前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
shehuiyuelaiyuehao5 小时前
算法50,分治归并,数组中的逆序对
java·算法
阳明山水5 小时前
校准分位数驱动智能库存决策
人工智能·深度学习·算法·机器学习·架构
91刘仁德6 小时前
C++ 继承和多态 设计模式
c语言·c++·笔记
码行山野赴时序归途6 小时前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表