784. Letter Case Permutation
idea: in this case, time : 2 ^ n , n is the number of letters in this string. space o(m), m is the number of total elements
S = "a1b2"
four levels
a A
1
b B
2
if current is letter, two options: upper or lower case, index + 1
if current is digit: do nothing , index + 1
stringBuilder or char[] array both work
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:
Swill be a string with length at most12.Swill consist only of letters or digits.
// use StringBuilder
class Solution { public List<String> letterCasePermutation(String S) { List<String> result = new ArrayList<>(); StringBuilder sb = new StringBuilder(); dfs(S, result, sb, 0); return result; } private void dfs(String S, List<String> result, StringBuilder sb, int index){ if(index == S.length()){ result.add(sb.toString()); return; // never forget again, otherwise boundary error } // check char a digit or letter char c = S.charAt(index); // Character.isLetter // Character.toUpperCase if(Character.isLetter(c)){ // add the lowercase int len = sb.length(); sb.append(Character.toLowerCase(c)); dfs(S, result, sb, index + 1); //sb is changed , so backtrack recovery sb.setLength(len); // add the uppercase sb.append(Character.toUpperCase(c)); dfs(S, result, sb, index + 1); sb.setLength(len); }else{ sb.append(c); dfs(S, result, sb, index + 1); } } }
// use charArray() class Solution { public List<String> letterCasePermutation(String S) { // since string s is immutable, we can other use stringBuilder or charArray char[] input = S.toCharArray(); List<String> result = new ArrayList<>(); dfs(input, result, 0); return result; } private void dfs(char[] input, List<String> result, int index){ if(index == input.length){ result.add(new String(input)); // not sure new String or .toString(); return; } //Character.isDigit() char c = input[index]; if(Character.isLetter(c)){ // add lowercase input[index] = Character.toLowerCase(c); dfs(input, result, index + 1); // add upper case input[index] = Character.toUpperCase(c); dfs(input, result, index + 1); }else{ // c is a digit dfs(input, result, index + 1); } } }
api:
convert a char[] array to string , use new String(input), input is the char[] array
convert a stringBuilder to string, use sb.toString(), sb is the stringBuilder
Character.isLetter(c), check if char c a letter
Character.isDigit(c)
Character.toLowerCase(c) make char c a lower case version of c
change the element value in an array
input[index] = Character.toUpperCase(c);
posted on 2018-07-18 08:08 猪猪🐷 阅读(151) 评论(0) 收藏 举报
浙公网安备 33010602011771号