forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LetterCasePermutations.java
51 lines (44 loc) · 1.55 KB
/
LetterCasePermutations.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*https://leetcode.com/problems/letter-case-permutation/*/
/*Prateekshya*/
class Solution {
List<String> result;
public List<String> letterCasePermutation(String s) {
result = new ArrayList<String>();
recur(s.toCharArray(),0,new StringBuffer(""));
return result;
}
public void recur(char[] chars, int index, StringBuffer curr)
{
//if all the characters are added, add it to the result and return
if (index == chars.length)
{
result.add(new String(curr));
return;
}
//get the ascii of the current character
int ascii = (int)chars[index];
//if the ascii lies between alphabets' range
if ((ascii >= 65 && ascii <=90) || (ascii >= 97 && ascii <= 122))
{
//get both case characters
char ch1 = chars[index];
char ch2 = ascii >= 65 && ascii <=90 ? (char)(ascii+32) : (char)(ascii-32);
//recur by adding first character
curr.append(ch1);
recur(chars, index+1, curr);
curr.delete(curr.length()-1,curr.length());
//recur by adding second character
curr.append(ch2);
recur(chars, index+1, curr);
curr.delete(curr.length()-1,curr.length());
}
//if not alphabet
else
{
//add the charcter and recur, no permutations needed
curr.append(chars[index]);
recur(chars, index+1, curr);
curr.delete(curr.length()-1,curr.length());
}
}
}