Leetcode 784. Letter Case Permutation
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. You can return the output in any order.
Example:
Input: s = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
We need to generate all possible permutations of the input string s
by toggling each letter between lowercase and uppercase. The digits remain unaffected. We can achieve this through a backtracking approach.
import java.util.ArrayList;
import java.util.List;
public class LetterCasePermutation {
public List<String> letterCasePermutation(String s) {
List<String> result = new ArrayList<>();
backtrack(s.toCharArray(), 0, result);
return result;
}
private void backtrack(char[] chars, int index, List<String> result) {
if (index == chars.length) {
result.add(new String(chars));
return;
}
if (Character.isDigit(chars[index])) {
backtrack(chars, index + 1, result);
} else {
// Lowercase branch
chars[index] = Character.toLowerCase(chars[index]);
backtrack(chars, index + 1, result);
// Uppercase branch
chars[index] = Character.toUpperCase(chars[index]);
backtrack(chars, index + 1, result);
}
}
public static void main(String[] args) {
LetterCasePermutation solution = new LetterCasePermutation();
String input = "a1b2";
List<String> output = solution.letterCasePermutation(input);
System.out.println(output);
}
}
The time complexity of this approach is (O(2^N)), where (N) is the number of letters in the string s
. This is because each letter can be toggled between lowercase and uppercase, resulting in (2^N) possible permutations.
The space complexity is also (O(2^N)) due to the storage of all permutations in the result list. The recursive call stack would also require space, contributing to the overall space usage.
This solution ensures that all possible permutations are effectively generated and collected.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?