讨论/题目交流/🏆 第 161 场力扣周赛/
🏆 第 161 场力扣周赛

欢迎小伙伴们在这里交流分享你的参赛心得以及体验。【前往竞赛

image.png

4 分 - 交换字符使得字符串相同
4 分 - 统计「优美子数组」
5 分 - 移除无效的括号
6 分 - 检查「好数组」

展开讨论

第一次做出来三题,可惜来晚了第三题没提交上
作为菜鸟,都是用的顶直观的写法,给同样实力不强的朋友们一点信心233


交换字符使得字符串相同

class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        unite = s1 + s2
        if unite.count('x') % 2 == 1:
            return -1
        if s1 == s2:
            return 0
        diffCount = 0
        x2y = 0
        for i in range(len(s1)):
            if s1[i] != s2[i]:
                diffCount += 1
                if s1[i] == 'x' and s2[i] == 'y':
                    x2y += 1
                    

        if x2y % 2 == 1:
            return int(diffCount / 2 + 1)
        return int(diffCount / 2)

统计「优美子数组」

class Solution:
    def numberOfSubarrays(self, nums: List[int], k: int) -> int:
        oddCount = 0
        oddIndex = []
        for i, n in enumerate(nums):
            if n % 2 == 1:
                oddCount += 1
                oddIndex.append(i)
        if oddCount < k:
            return 0
        
        niceCount = 0
        for i in range(oddCount-k+1):
            if i == 0:
                aheadNum = oddIndex[0] + 1
            else:
                aheadNum = oddIndex[i] - oddIndex[i-1]
            if i+k == oddCount:
                afterNum = len(nums) - oddIndex[-1]
            else:
                afterNum = oddIndex[i+k] - oddIndex[i+k-1]
                
            niceCount += aheadNum * afterNum
        return niceCount

移除无效的括号

class Solution:
    def minRemoveToMakeValid(self, s: str) -> str:
        temp = [c for c in s]
        removed = 0
        wait = []
        for i, c in enumerate(s):
            if c == '(':
                wait.append(i)
            elif c == ')':
                if len(wait) != 0:
                    wait.pop()
                else:
                    temp.pop(i-removed)
                    removed += 1

        for i in range(len(wait)):
            tempStr = ''.join(temp)
            toPop = tempStr.rindex('(')
            temp.pop(toPop)
            
        return ''.join(temp)
        
1
展开全部 25 讨论