784. Letter Case Permutation
Problem
Change the case of any of the letters in s (digits stay as they are) and return every string you can get, in any order.
Example: "a1b2" → ["a1b2","a1B2","A1b2","A1B2"]
Constraints: length ≤ 12.
Each letter branches into lower/upper; digits don't branch. Building iteratively: for each letter, double the result list.
Complexity: O(2^L · n).
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
res = [""]
for ch in s:
if ch.isalpha():
res = [p + c for p in res for c in (ch.lower(), ch.upper())]
else:
res = [p + ch for p in res]
return res
assert sorted(Solution().letterCasePermutation("a1b2")) == ["A1B2", "A1b2", "a1B2", "a1b2"]
assert Solution().letterCasePermutation("3z4") == ["3z4", "3Z4"]
class Solution {
public List<String> letterCasePermutation(String s) {
List<String> res = new ArrayList<>();
bt(s.toCharArray(), 0, res);
return res;
}
private void bt(char[] c, int i, List<String> res) {
if (i == c.length) { res.add(new String(c)); return; }
if (Character.isLetter(c[i])) {
c[i] = Character.toLowerCase(c[i]); bt(c, i + 1, res);
c[i] = Character.toUpperCase(c[i]); bt(c, i + 1, res);
} else bt(c, i + 1, res);
}
}
func letterCasePermutation(s string) []string {
res := []string{""}
for i := 0; i < len(s); i++ {
ch := s[i]
next := []string{}
for _, p := range res {
if unicode.IsLetter(rune(ch)) { // branch: lower then upper
next = append(next, p+strings.ToLower(string(ch)), p+strings.ToUpper(string(ch)))
} else {
next = append(next, p+string(ch))
}
}
res = next
}
return res
}