[leetcode] 784. Letter Case Permutation @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86580919

原题

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.

Examples:
Input: S = “a1b2”
Output: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]

Input: S = “3z4”
Output: [“3z4”, “3Z4”]

Input: S = “12345”
Output: [“12345”]
Note:

S will be a string with length between 1 and 12.
S will consist only of letters or digits.

解法1

参考: 【LeetCode】784. Letter Case Permutation 解题报告(Python & C++)
回朔法 + DFS. DFS的参数一般有index, path, res. DFS的结束条件是index等于字符串的长度,此时我们已经走完字符串了, 因此将path加到结果中并返回.
Time: O(2^n), n为字符串中字母的个数
Space: O(1)

代码

class Solution(object):
    def letterCasePermutation(self, S):
        """
        :type S: str
        :rtype: List[str]
        """
        def dfs(s, index, path, res):
            if index == len(s):
                res.append(path)
                return
            else:
                if s[index].isalpha():
                    dfs(s, index+1, path + s[index].lower(), res)
                    dfs(s, index+1, path + s[index].upper(), res)
                else:
                    dfs(s, index+1, path + s[index], res)
                
        res = []       
        dfs(S, 0, '', res)
        return res
    

解法2

循环法, 初始化res为[’’], 代表现有的path,然后遍历字符串, 如果当前字符串是字母, 那么将res里所有的path分别加上字母的大写和小写, 如果当前字符串是数字, 那么将res里所有的path加上数字即可.
Time: O(n)
Space: O(1)

代码

class Solution(object):
    def letterCasePermutation(self, S):
        """
        :type S: str
        :rtype: List[str]
        """
        res = ['']
        for ch in S:
            if ch.isalpha():
                res = [path + letter for path in res for letter in [ch.lower(), ch.upper()]]
            else:
                res = [path + ch for path in res]
                
        return res

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86580919