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;
}
相关推荐
ZhengEnCi4 小时前
Agent 架构怎么选:从单 Agent 到多 Agent 编排的选型决策指南
算法·架构
秋天的怀念_David5 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Pniubi5 小时前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
hhb_6185 小时前
大模型落地三重优化实战
人工智能·算法·机器学习
云和数据.ChenGuang5 小时前
光哥说Python RAG 系统需要哪些评估指标:从检索到生成的全链路评测指南
网络·人工智能·python·算法·langchain
2601_970703837 小时前
工业除湿机租赁:把一份租金合同拆开看
大数据·数据结构·算法·数据库架构·推荐算法
心中有你02147 小时前
Java实现Dijkstra最短路径算法(邻接表 + 优先队列)
java·数据库·算法
ZhengEnCi8 小时前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Zwawa8 小时前
串口为什么会丢字节:从轮询到中断和环形缓冲区
c语言·单片机·嵌入式
Flynn Liang8 小时前
RAG 答非所问/幻觉怎么破?Spring AI QuestionAnswerAdvisor 召回优化实战(TopK/重排/混合检索)
人工智能·算法·spring·rag·幻觉·springai