Skip to content

Commit 4ebd285

Browse files
Letter Case Permutation: Accepted
1 parent 251e1ff commit 4ebd285

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ My accepted leetcode solutions to some of the common interview problems.
5757
- [Regular Expression Matching](problems/src/backtracking/RegularExpressionMatching.java) (Hard)
5858
- [Expression Add Operators](problems/src/backtracking/ExpressionAddOperators.java) (Hard)
5959
- [Wildcard Matching](problems/src/backtracking/WildcardMatching.java) (Hard)
60+
- [Letter Case Permutation](problems/src/backtracking/LetterCasePermutation.java) (Easy)
6061

6162
#### [Binary Search](problems/src/binary_search)
6263

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)