0129leetcode brushes 5 python questions

8

Title description:
Please implement a myAtoi(string s) function to convert a string into a 32-bit signed integer (similar to the atoi function in C/C++).
The algorithm of the function myAtoi(string s) is as follows:
read the string and discard the useless leading spaces.
Check whether the first character (assuming the end of the character has not been reached ) is positive or negative, and read the character (if any). Determine whether the final result is negative or positive. If neither exists, the result is assumed to be positive.
Read in the next character until the next non-numeric character is reached or the end of the input is reached. The rest of the string will be ignored.
Convert the numbers read in the previous steps into integers (ie, "123" -> 123, "0032" -> 32). If no number is read, the integer is 0. Change the symbol if necessary (from step 2).
If the integer number exceeds the 32-bit signed integer range [−231, 231 − 1], the integer needs to be truncated to keep it within this range. Specifically, integers less than −231 should be fixed to −231, and integers greater than 231 − 1 should be fixed to 231 − 1.
Return an integer as the final result.

Example:
Insert picture description here
Answer:

class Solution:
    def myAtoi(self, s: str) -> int:
        '''
        使用正则表达式 
        ^:匹配字符串开头,
        [\+\-]:代表一个+字符或-字符,
        ?:前面一个字符可有可无,
        \d:一个数字,
        +:前面一个字符的一个或多个,
        \D:一个非数字字符
        max(min(数字, 2**31 - 1), -2**31) 用来防止结果越界
        '''
        return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)
        

22

Title description: The
number n represents the logarithm of generating brackets. Please design a function to generate all possible and effective bracket combinations.

Example:
Insert picture description here
Answer:

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n==0:
            return [""]
        elif n==1:
            return ["()"]
        elif n==2:
            return ["()()","(())"]
        result=[]
        for i in range(n):
            j=n-1-i
            temp1=self.generateParenthesis(i)
            temp2=self.generateParenthesis(j)
            result.extend(["(%s)%s"%(p,q)for p in temp1 for q in temp2])
        return result

47

Title description:
Given a sequence nums that can contain repeated numbers, return all non-repeated full permutations in any order.

Example:
Insert picture description here
Answer:

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        return list(set(itertools.permutations(nums)))

833

Title description: A
certain string S needs to perform some replacement operations, replacing the original letter group with a new letter group (not necessarily the same size).
Each replacement operation has 3 parameters: start index i, source word x and target word y. The rule is: if x starts at position i in the original string S, then replace the occurrence of x with y. If not, do nothing.
For example, if S = "abcd" and the replacement operation i = 2, x = "cd", y = "ffff", then because "cd" starts at position 2 in the original string S, use "ffff" Replace it.
Let's look at another example on S = "abcd". If a replacement operation i = 0, x = "ab", y = "eee", and another replacement operation i = 2, x = "ec", y = "Ffff", then the second operation will not be executed, because S[2] ='c' in the original string does not match x[0] ='e'.
All these operations happen at the same time. Ensure that there is no overlap when replacing: S = "abc", indexes = [0, 1], sources = ["ab", "bc"] is not a valid test case.

Example:
Insert picture description here
Answer:

class Solution:
    def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
        arr=[]
        prev=len(S)
        for i,s,t in sorted(zip(indexes,sources,targets),reverse=True):
            arr.append(S[i:i+len(s)].replace(s,t)+S[i+len(s):prev])
            prev=i
        return S[:prev]+''.join(arr[::-1])

890

Title description:
You have a word list words and a pattern pattern. You want to know which words in words match the pattern.
If there is a permutation p of letters, so that after replacing each letter x in the pattern with p(x), we get the required word, and the word matches the pattern.
(Recall that the arrangement of letters is a bijection from letter to letter: each letter maps to another letter, and no two letters map to the same letter.)
Return a list of words in words that match the given pattern.
You can return the answers in any order.

Example:
Insert picture description here
Answer:

class Solution:
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        res = []
        for word in words:
            if len(set(list(word))) == len(set(list(pattern))) == len(set(zip(list(word),list(pattern)))):
                res.append(word)
        return res

Guess you like

Origin blog.csdn.net/yeqing1997/article/details/113176823