Leetcode-Weekly Contest 170 题解&总结

Leetcode-Weekly Contest 170 题解&总结

    20年算法刷题上路,来打个周赛试试水~
    Link: https://leetcode.com/contest/weekly-contest-170
  1. Decrypt String from Alphabet to Integer Mapping
class Solution(object):
    def freqAlphabets(self, s):
        """
        :type s: str
        :rtype: str
        """
        dst = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", 
               "u", "v", "w", "x", "y", "z"]
        i, lens = 0, len(s)
        res = ""
        
        while i < lens:
            if s[i] >= '1' and s[i] <= '9':
                if i + 2 < lens:
                    if s[i + 2] != '#':
                        res += chr(ord('a') + ord(s[i]) - 49)
                        i += 1
                    else:
                        num = (ord(s[i]) - 48) * 10 + (ord(s[i + 1]) - 48)
                        res += dst[num - 1]
                        i += 3
                else:
                    res += chr(ord('a') + ord(s[i]) - 49)
                    i += 1
        return res
  1. XOR Queries of a Subarray
class Solution(object):
    def xorQueries(self, arr, queries):
        """
        :type arr: List[int]
        :type queries: List[List[int]]
        :rtype: List[int]
        """
        len_arr, len_queries = len(arr), len(queries)
        xor = 0
        pre = [0] * len_arr
        res = [0] * len_queries
        
        for i in range(len_arr):
            pre[i] = xor ^ arr[i]
            xor = pre[i]
        # print(pre)
        
        for i in range(len_queries):
            if queries[i][0] == 0:
                res[i] = pre[queries[i][1]]
            else:
                res[i] = pre[queries[i][0] - 1] ^ pre[queries[i][1]]
        
        return res
  1. Get Watched Videos by Your Friends
  2. Minimum Insertion Steps to Make a String Palindrome
class Solution(object):
    def minInsertions(self, s):
        """
        :type s: str
        :rtype: int
        """
        lens = len(s)
        dp = [[0] * (lens + 1) for _ in range(lens + 1)]
        
        t = "".join(reversed(s))
        
        for i in range(lens):
            for j in range(lens):
                if s[i] == t[j]:
                    dp[i + 1][j + 1] = dp[i][j] + 1
                else:
                    dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
        # print(dp)
        return lens - dp[lens][lens]

你可能感兴趣的:(Leetcode)