|
| 1 | +package backtracking; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by gouthamvidyapradhan on 12/04/2018. |
| 8 | + * Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. |
| 9 | + * Return a list of all possible strings we could create. |
| 10 | + * <p> |
| 11 | + * Examples: |
| 12 | + * Input: S = "a1b2" |
| 13 | + * Output: ["a1b2", "a1B2", "A1b2", "A1B2"] |
| 14 | + * <p> |
| 15 | + * Input: S = "3z4" |
| 16 | + * Output: ["3z4", "3Z4"] |
| 17 | + * <p> |
| 18 | + * Input: S = "12345" |
| 19 | + * Output: ["12345"] |
| 20 | + * Note: |
| 21 | + * <p> |
| 22 | + * S will be a string with length at most 12. |
| 23 | + * S will consist only of letters or digits. |
| 24 | + * |
| 25 | + * Solution: O(N x 2 ^ N) Backtrack and generate all possible combinations. |
| 26 | + */ |
| 27 | +public class LetterCasePermutation { |
| 28 | + |
| 29 | + /** |
| 30 | + * Main method |
| 31 | + * |
| 32 | + * @param args |
| 33 | + * @throws Exception |
| 34 | + */ |
| 35 | + public static void main(String[] args) throws Exception { |
| 36 | + System.out.println(new LetterCasePermutation().letterCasePermutation("a1b2")); |
| 37 | + } |
| 38 | + |
| 39 | + public List<String> letterCasePermutation(String S) { |
| 40 | + List<String> result = new ArrayList<>(); |
| 41 | + backtrack(S, result, 0, ""); |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + private void backtrack(String s, List<String> result, int i, String r) { |
| 46 | + if (i == s.length()) { |
| 47 | + result.add(r); |
| 48 | + } else { |
| 49 | + if (Character.isAlphabetic(s.charAt(i))) { |
| 50 | + backtrack(s, result, i + 1, r + s.charAt(i)); |
| 51 | + if (Character.isLowerCase(s.charAt(i))) { |
| 52 | + backtrack(s, result, i + 1, r + Character.toUpperCase(s.charAt(i))); |
| 53 | + } else { |
| 54 | + backtrack(s, result, i + 1, r + Character.toLowerCase(s.charAt(i))); |
| 55 | + } |
| 56 | + } else { |
| 57 | + backtrack(s, result, i + 1, r + s.charAt(i)); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments