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;
}
相关推荐
电科_银尘12 小时前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴15 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David15 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
戊本菌17 小时前
进程(三)进程优先级:谁先上 CPU
linux·c语言·硬件架构
LK_0718 小时前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi19 小时前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK19 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set
文丑颜不良啊19 小时前
LeetCode3341~3360题目解析
java·leetcode
上海潭龙东海科技有限公司20 小时前
智慧堆场动态模型三维实时孪生重构智能管控
大数据·网络·数据库·算法·重构
嵌入式 Linux手记21 小时前
一块内存,三种解释:union 的真实用法
linux·c语言·驱动开发·嵌入式