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.

答案

class Solution {
    public List letterCasePermutation(String S) {
        List list = new ArrayList();
        StringBuilder sb = new StringBuilder(S);
        recur(list, 0, sb);
        return list;
    }
    public void recur(List list, int index, StringBuilder sb) {
        if(index == sb.length()) {
            list.add(sb.toString());
            return;
        }
        
        char c = sb.charAt(index);
        if(Character.isLetter(c)) {
            // case unchanged
            recur(list, index + 1, sb);
            
            // flip case
            if(Character.isUpperCase(c))
                sb.setCharAt(index, Character.toLowerCase(c));
            else
                sb.setCharAt(index, Character.toUpperCase(c));
            recur(list, index + 1, sb);

        }
        else {
            // Keep recursing
            recur(list, index + 1, sb);
        }
    }
    
}

你可能感兴趣的:(Letter Case Permutation)