leetcode 1221. Split a String in Balanced Strings 解法 python

本文介绍了一种算法,用于将包含'L'和'R'字符的平衡字符串分割成最大数量的平衡子字符串。通过遍历字符串并计数'L'和'R'出现的次数,当两者相等时,表示找到一个平衡子序列,从而实现最大分割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

一.问题描述

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

Given a balanced string s split it in the maximum amount of balanced strings.

Return the maximum amount of splitted balanced strings.

 

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 = "RLLLLRRRLR"
Output: 3
Explanation: s can be split into "RL", "LLLRRR", "LR", each substring contains same number of 'L' and 'R'.

Example 3:

Input: s = "LLLLRRRR"
Output: 1
Explanation: s can be split into "LLLLRRRR".

 

Constraints:

  • 1 <= s.length <= 1000
  • s[i] = 'L' or 'R'

二.解决思路

要将原序列分割成多个子平衡序列。

顺序遍历,一边遍历一边保存出现的r和l的次数,并判断r和l次数是否相同,相同的话则是一个平衡序列,然后清空计数器进行下一次计算,因为是分割序列,所以必然平衡子序列是一个接着一个的。

为了减少一次if语句的判断,我将l和r与索引map。

同时发现一个用库函数一行代码解决的方法。也放在源码部分了。

更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我

欢迎大家一起套路一起刷题一起ac

三.源码

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        cnt=[0,0]
        ch_to_num={'L':0,'R':1}
        rst=0
        for ch in s:
            cnt[ch_to_num[ch]]+=1
            if cnt[ch_to_num[ch]]==cnt[ch_to_num[ch]-1]:
                rst+=1
                cnt[ch_to_num[ch]],cnt[ch_to_num[ch]-1]=0,0
        return rst

一行代码解决:作者:https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403975/Python3-1-liner

from itertools import accumulate as acc
class Solution:
    def balancedStringSplit(self, s: str) -> int:
        return list(acc(1 if c == 'L' else -1 for c in s)).count(0)

关于accumulate函数在我上一篇博客有讲。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值