【leetcode-python-23】1221. 分割平衡字符串

【leetcode-python-23】1221. 分割平衡字符串

  • 渣渣原始版(92.73%)
  • 参考官方版(27.64%)

leetcode 1221. 分割平衡字符串

渣渣原始版(92.73%)

class Solution(object):
    def balancedStringSplit(self, s):
        """
        :type s: str
        :rtype: int
        """

        if not s:
            return 0
        
        n = 0
        x = s[0]
        num = 0
        
        for i in range(len(s)-1):
            if s[i] == x:
                n += 1
            else:
                n -= 1
                
            if n == 0:
                x = s[i+1]
                num += 1
            
        return num+1

参考官方版(27.64%)

直接判断是L,还是R。
注:参考题解区官方思路。

class Solution(object):
    def balancedStringSplit(self, s):
        """
        :type s: str
        :rtype: int
        """

        n = 0
        num = 0
        
        for i in s:
            if i == "L":
                n += 1
            else:
                n -= 1
                
            if n == 0:
                num += 1
            
        return num

新手入坑,多多包涵~~

你可能感兴趣的:(My,leetcode,leetcode,python,数据结构)