Letter Case Permutation
给一个字符串S, 返回把字符串中的字母随意大小写后, 所有的组合.
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 |
class Solution { Set<String> set = new HashSet<>(); public List<String> letterCasePermutation(String S) { return letterCasePermutation(S, 0); } public List<String> letterCasePermutation(String S, int j) { List<String> res = new ArrayList<>(); for(int i = j ; i < S.length(); i++){ if(Character.isLetter(S.charAt(i))) { String low = S.substring(0,i) + Character.toLowerCase(S.charAt(i)) + S.substring(i+1, S.length()); if (!set.contains(low)) { set.add(low); res.add(low); res.addAll(letterCasePermutation(low, i + 1)); } String high = S.substring(0,i) + Character.toUpperCase(S.charAt(i)) + S.substring(i+1, S.length()); if(!set.contains(high)) { set.add(high); res.add(high); res.addAll(letterCasePermutation(high, i + 1)); } } else { if(!set.contains(S)) { set.add(S); res.add(S); } } } return res; } } |