LWC 72: 784. Letter Case Permutation

Posted Demon的黑与白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LWC 72: 784. Letter Case Permutation相关的知识,希望对你有一定的参考价值。

LWC 72: 784. Letter Case Permutation

传送门:784. Letter Case Permutation

Problem:

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 at most 12.
  • S will consist only of letters or digits.

思路:
dfs即可,遇到数字跳过,遇到字母,分为两种情况传给子问题。

Java版本:

    public List<String> letterCasePermutation(String S) 
        all = new ArrayList<>();
        backtrack(S.toCharArray(), 0, "");
        return all;
    

    List<String> all;
    public void backtrack(char[] cs, int pos, String ans) 
        if (pos == cs.length) 
            all.add(ans);
            return;
        
        else 
            if (Character.isAlphabetic(cs[pos])) 
                char l = cs[pos];
                backtrack(cs, pos + 1, ans + l);
                if (l >= 'a' && l <= 'z') l = (char) (l - 'a' + 'A');
                else if (l >= 'A' && l <= 'Z') l = (char) (l - 'A' + 'a');
                backtrack(cs, pos + 1, ans + l);
            
            else 
                backtrack(cs, pos + 1, ans + cs[pos]);
            
        
    

Python版本:

class Solution(object):
    def letterCasePermutation(self, S):
        """
        :type S: str
        :rtype: List[str]
        """
        ans = []

        def dfs(S, pos, str):
            if pos == len(S):
                ans.append(str)
                return
            else:
                if S[pos].isalpha():
                    letter = S[pos]
                    dfs(S, pos + 1, str + letter.upper())
                    dfs(S, pos + 1, str + letter.lower())
                else:
                    dfs(S, pos + 1, str + S[pos])
        dfs(S, 0, '')
        return ans

以上是关于LWC 72: 784. Letter Case Permutation的主要内容,如果未能解决你的问题,请参考以下文章

784. Letter Case Permutation

784. Letter Case Permutation

784. Letter Case Permutation

784. Letter Case Permutation - Easy

LeetCode 784. Letter Case Permutation (字母大小写全排列 )

784. Letter Case Permutation---back tracking