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 between 1 and 12.
  • S will consist only of letters or digits.

classical dfs

dfs helper function有三个参数,其中idx记录recursion level,当递归到最后一层时,把当前string加入res中并返回

然后判断当前字符是数字还是字母:如果是数字,直接递归到下一层并返回;如果是字母,分别转换成大、小写字母,再递归

time = O(2^n), space = O(n)

class Solution {
    public List<String> letterCasePermutation(String S) {
        List<String> res = new ArrayList<>();
        if(S == null || S.length() == 0) {
            return res;
        }
        dfs(S, 0, res);
        return res;
    }
    
    public void dfs(String S, int idx, List<String> res) {
        if(idx == S.length()) {
            res.add(new String(S));
            return;
        }
        char[] chs = S.toCharArray();
        
        if(S.charAt(idx) >= '0' && S.charAt(idx) <= '9') {
            dfs(S, idx + 1, res);
            return;
        }
        
        chs[idx] = Character.toUpperCase(chs[idx]);
        dfs(String.valueOf(chs), idx + 1, res);
        
        chs[idx] = Character.toLowerCase(chs[idx]);
        dfs(String.valueOf(chs), idx + 1, res);
    }
}

or 先把string全部转换成小写字母的char array

class Solution {
    public List<String> letterCasePermutation(String S) {
        List<String> res = new ArrayList<>();
        if(S == null || S.length() == 0) {
            return res;
        }
        char[] chs = S.toLowerCase().toCharArray();
        dfs(chs, 0, res);
        return res;
    }
    
    public void dfs(char[] chs, int idx, List<String> res) {
        if(idx == chs.length) {
            res.add(new String(chs));
            return;
        }
        
        dfs(chs, idx + 1, res);
        
        if(Character.isLetter(chs[idx])) {
            chs[idx] = Character.toUpperCase(chs[idx]);
            dfs(chs, idx + 1, res);
            chs[idx] = Character.toLowerCase(chs[idx]);
        }
    }
}
原文地址:https://www.cnblogs.com/fatttcat/p/11217297.html