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;
}
相关推荐
天疆说27 分钟前
庞特里亚金极小值原理的详细推导
算法
余俊晖39 分钟前
Self-OPD:去掉教师机的流匹配模型 On-Policy 蒸馏
人工智能·算法·机器学习
手写码匠41 分钟前
华为云Flexus+DeepSeek征文|华为云MaaS DeepSeek推理服务 × Flexus云服务器 × Dify一键部署:性能评测实战
人工智能·深度学习·算法·aigc
en.en..1 小时前
C语言 static函数与头文件封装规范
java·c语言·前端
啥都想学点的研究生2 小时前
一篇文章讲清楚:逻辑回归
算法·机器学习·逻辑回归
布莱克6052 小时前
栈(Stack)详解:定义、作用、应用场景及与队列的区别(附 C/C++ 代码)
c语言·开发语言·c++·
wuyk5552 小时前
从零吃透 Modbus 通信|第 6 章:线圈功能码 05/0F 实现 & Modbus‑TCP 基础入门
c语言·网络·网络协议·tcp/ip
货拉拉技术3 小时前
Agent 场景下 Token 成本优化的实战技巧
算法
hahaha60163 小时前
HLS高层次综合设计技巧--循环merge和循环split
人工智能·算法·计算机视觉