码迷,mamicode.com
首页 > 其他好文 > 详细

784. Letter Case Permutation - Easy

时间:2019-07-20 13:01:37      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:return   rac   UNC   transform   递归   参数   note   ssi   function   

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]);
        }
    }
}

 

784. Letter Case Permutation - Easy

标签:return   rac   UNC   transform   递归   参数   note   ssi   function   

原文地址:https://www.cnblogs.com/fatttcat/p/11217297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!