leetcode 1221. Split a String in Balanced Strings ( Python )

514 阅读1分钟

描述

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".

Example 4:

Input: s = "RLRRRLLRLL"
Output: 2
Explanation: s can be split into "RL", "RRRLLRLL", since each substring contains an equal number of 'L' and 'R'

解析

根据题意,平衡字符串是 L 和 R 数量相等的字符串,题意要找出可以拆分出来的最大个数的子平衡字符串,其实就是类似于括号问题。遍历字符串,若遇到一个 L(R) ,n 自增 1 ,若遇到一个 R(L),n 自减 1 ,当 n 为 0 时,则相当于能分出来一个子平衡字符串。

解答

class Solution(object):
    def balancedStringSplit(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0
        n = 0
        for c in s:
            if c=='L':
                n+=1
            else:
                n-=1
            if n==0:
                count+=1
        return count

运行结果

Runtime: 20 ms, faster than 53.38% of Python online submissions for Split a String in Balanced Strings.
Memory Usage: 11.8 MB, less than 100.00% of Python online submissions for Split a String in Balanced Strings.
请作者喝吃泡芙 支付宝

支付宝

微信

微信