Skip to content

800. Letter Case Permutation

String Backtracking Bit Manipulation

Problem - Letter Case Permutation

Medium

Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.

Return a list of all possible strings we could create. Return the output in any order.

 

Example 1:

Input: s = "a1b2"
Output: ["a1b2","a1B2","A1b2","A1B2"]

Example 2:

Input: s = "3z4"
Output: ["3z4","3Z4"]

 

Constraints:

  • 1 <= s.length <= 12
  • s consists of lowercase English letters, uppercase English letters, and digits.

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def letterCasePermutation(self, s: str) -> List[str]:
        # result = []
        # n = sum(char.isalpha() for char in s)

        # for i in range(1 << n):
        #     j, tmp = 0, []
        #     for char in s:
        #         if char.isalpha():
        #             char = char.lower() if (i >> j) & 1 else char.upper()
        #             j += 1
        #         tmp.append(char)
        #     result.append("".join(tmp))

        # return result

        result = [""]
        for char in s:
            if char.isdigit():
                result = [rchar + char for rchar in result]
            else:
                result = [rchar + val for rchar in result for val in (char.upper(), char.lower())]

        return result

Submission Stats:

  • Runtime: 3 ms (89.59%)
  • Memory: 18.7 MB (69.06%)