The Letter Case Permutation problem involves generating all possible strings by changing the case of each letter in the input string. Digits remain unchanged.
class Solution {
public List<String> letterCasePermutation(String s) {
List<String> result = new ArrayList<>();
backtrack(0, s.toCharArray(), result);
return result;
}
private void backtrack(int index, char[] chars, List<String> result) {
if (index == chars.length) {
result.add(new String(chars));
return;
}
if (Character.isLetter(chars[index])) {
// Change to lowercase
chars[index] = Character.toLowerCase(chars[index]);
backtrack(index + 1, chars, result);
// Change to uppercase
chars[index] = Character.toUpperCase(chars[index]);
backtrack(index + 1, chars, result);
} else {
// Skip digits
backtrack(index + 1, chars, result);
}
}
}
O(2^N)
, where N
is the number of letters in the input string. Each letter has two possibilities (uppercase or lowercase).O(N)
, for the recursion stack.Input: s = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Explanation:
- For each letter, toggle between lowercase and uppercase.
- Digits remain unchanged.