The four Day 給出一個平衡字符串,將它分割成儘量多的平衡字符串

"""
在一個「平衡字符串」中,'L' 和 'R' 字符的數量是相同的。

給出一個平衡字符串 s,請你將它分割成儘量多的平衡字符串。

返回能夠經過分割獲得的平衡字符串的最大數量。

示例 1:

輸入:s = "RLRRLLRLRL"
輸出:4
解釋:s 能夠分割爲 "RL", "RRLL", "RL", "RL", 每一個子字符串中都包含相同數量的 'L' 和 'R'。

來源:力扣(LeetCode)
連接:https://leetcode-cn.com/problems/split-a-string-in-balanced-strings
著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。
"""
"""
@author : jiyanjiao
@date :2019-10-24
"""


class Solution(object):
    def balancedStringSplit(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0
        count_L = 0
        count_R = 0
        flag = 0
        
        s_list = list(s)
        for s_ in s:
            if s_ == 'L':
                count_L += 1
            else:
                count_R += 1
            if count_L == count_R:
                count += 1
                total = count_L + count_R
                # 用flag來標記上次已經識別到的位置
                for i in range(flag, total):
                    print(s_list[i], end='')
                print(',', end=' ')
                flag = total
        return count
 
    
if __name__ == '__main__':
    s = Solution()
    s.balancedStringSplit("RLRRLLRLRL")
相關文章
相關標籤/搜索