forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_784.java
68 lines (59 loc) · 1.9 KB
/
_784.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 784. Letter Case Permutation
*
* Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.
* Return a list of all possible strings we could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: S = "3z4"
Output: ["3z4", "3Z4"]
Input: S = "12345"
Output: ["12345"]
Note:
S will be a string with length at most 12.
S will consist only of letters or digits.
*/
public class _784 {
public static class Solution1 {
public List<String> letterCasePermutation(String S) {
Set<String> result = new HashSet<>();
result.add(S);
for (int i = 0; i < S.length(); i++) {
if (Character.isAlphabetic(S.charAt(i))) {
Set<String> newResult = new HashSet<>();
for (String word : result) {
if (Character.isUpperCase(word.charAt(i))) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i; j++) {
sb.append(word.charAt(j));
}
sb.append(Character.toLowerCase(word.charAt(i)));
for (int j = i + 1; j < word.length(); j++) {
sb.append(word.charAt(j));
}
newResult.add(sb.toString());
} else {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < i; j++) {
sb.append(word.charAt(j));
}
sb.append(Character.toUpperCase(word.charAt(i)));
for (int j = i + 1; j < word.length(); j++) {
sb.append(word.charAt(j));
}
newResult.add(sb.toString());
}
}
result.addAll(newResult);
}
}
return new ArrayList<>(result);
}
}
}