leetcode刷题记录791-800 python版

前言

继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,感谢各位大佬

791. 自定义字符串排序

class Solution:
    def customSortString(self, S: str, T: str) -> str:
        import collections
        c = collections.Counter(T)
        res, l = '', []
        for i in c:
            if i in S:
                l.append(i)  # 将T中出现且在S中出现的字母存储起来
            else:
                res = res + c[i] * i  # 将T中出现,却在S中未出现直接进行重复
        for j in S:
            if j in l:  # ss是按照S中的相对位置读出的,如果ss在T中出现过,就按要求进行复制
                res = res + c[j] * j
        return res

792. 匹配子序列的单词数

class Solution:
    def numMatchingSubseq(self, S: str, words: List[str]) -> int:
        count = 0
        for i in words:
            num = 0
            pos = -1
            for j in i:
                pos = S.find(j,pos+1) # 从pos+1位置往后找,找不到返回-1
                if pos == -1:
                    break
                else:
                    num = num+1
            if num == len(i):
                count = count+1
        return count

793. 阶乘函数后K个零

class Solution:
    def preimageSizeFZF(self, K: int) -> int:
        #结果只有两种,要么是5要么是0
       stack=[(5**i-1)/4 for i in range(1,14)]
       stack.reverse()
       for i in range(13):
           if stack[i]<=K:
               if K==stack[i]*5:
                   return 0
               else:
                   K=K%stack[i]
       return 5

794. 有效的井字游戏

class Solution:
    def validTicTacToe(self, board: List[str]) -> bool:
        import collections
        '''
        与其说是程序,不如说是逻辑
        就算是平常有个人问你,你也得认真分析,并不是用算法去套

        1. X>=O的,因为X先下
        2. O+1>=X的,因为两者之间最大就差1

        在数目上没有问题之后,来看局面:
        3. 如果当前棋局没有结束,那么一定是可行的!
        4. 如果当前棋局已经结束了:
            X胜:X=O+1。X,O;X,O;X,O……;X
            O胜:X==O

        其他情况,肯定是错的
        '''
        cnt = collections.Counter(''.join(board))

        if cnt['X'] < cnt['O'] or cnt['X'] > cnt['O'] + 1:
            print('数目不对!')
            return False

        def whowins(board):
            X_win = False
            O_win = False
            # row
            for row in board:
                if row[0] != ' ' and len(set(row)) == 1:
                    if row[0] == 'X':
                        X_win = True
                    else:
                        O_win = True
            # col
            for col in range(3):
                if board[0][col] != ' ' and board[0][col] == board[1][col] == board[2][col]:
                    if board[0][col] == 'X':
                        X_win = True
                    else:
                        O_win = True
            # diagonal
            if board[1][1] != ' ' and (board[0][0] == board[1][1] == board[2][2] \
                                       or board[0][2] == board[1][1] == board[2][0]):
                if board[1][1] == 'X':
                    X_win = True
                else:
                    O_win = True

            if X_win and O_win:
                return 'XO'
            elif X_win:
                return 'X'
            elif O_win:
                return 'O'
            else:
                return -1

        winner = whowins(board)
        print(f'Winner=={winner}')

        if winner == -1:
            print('没人赢,所以应该可行!')
            return True
        elif winner == 'XO':
            print("不可能两个赢家!")
            return False
        elif winner == 'X':
            print("X赢了,要求{cnt['X']}=={cnt['O']+1}")
            return cnt['X'] == cnt['O'] + 1
        elif winner == 'O':
            print("O赢了,要求{cnt['X']}=={cnt['O']+1}")
            return cnt['X'] == cnt['O']
        else:
            print('ERROR!!!')
        return False

795. 区间子数组个数

class Solution:
    def numSubarrayBoundedMax(self, A: List[int], L: int, R: int) -> int:
        res, tmp = 0, 0
        pre = -1
        for i, num in enumerate(A):
            if num < L:
                res += tmp
            elif num > R:
                tmp = 0
                pre = i
            else:
                tmp = i - pre
                res += tmp
        return res

796. 旋转字符串

# 这题怎么感觉出现过了
class Solution:
    def rotateString(self, A: str, B: str) -> bool:
        return len(A) == len(B) and B in A+A

797. 所有可能的路径

class Solution:
    def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
        def dfs(current: int) -> List[List[int]]:
            if current == len(graph) - 1:
                return [[current]]
            paths = []
            for nxt in graph[current]:
                paths.extend([[current, *p] for p in dfs(nxt)])
            return paths
        return dfs(0)

798. 得分最高的最小轮调

#这解法nb了
class Solution:
    def bestRotation(self, A: List[int]) -> int:
        #score[k]:表示移动K步后,当前分数应该加几分,正数为加,负数为扣
        score = [0] * len(A)
        for i in range(len(A)):
            score[(i + len(A) - A[i] + 1) % len(A)] -= 1
        for i in range(1, len(A)):
            score[i] += score[i - 1] + 1
        return score.index(max(score))

799. 香槟塔

class Solution:
    def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
        cur = [poured]
        # 执行第i层往下倒
        for i in range(query_row):
            Next = [0] * (i + 2)
            for j in range(len(cur)):
                if cur[j] > 1:
                    Next[j] += (cur[j] - 1) / 2
                    Next[j + 1] += (cur[j] - 1) / 2
            cur = Next
        return 1 if cur[query_glass] >= 1 else cur[query_glass]

你可能感兴趣的:(leetcode,leetcode,python)