784. Letter Case Permutation

Problem:
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"]
Analysis:
See implementation

Solution:

class Solution {
    public List<String> letterCasePermutation(String S) {
        List<String> res = new ArrayList<>();
        
        helper(res, 0, new StringBuilder(), S);
        return res;
    }

    private void helper(List<String> res, int index, StringBuilder sb, String S) {
        if (index == S.length()) {
            res.add(sb.toString());
            return;
        }
        char c = S.charAt(index);
        if (Character.isLetter(c)) {
            sb.append(Character.toLowerCase(c));
            helper(res, index + 1, sb, S);
            sb.setLength(sb.length() - 1);

            sb.append(Character.toUpperCase(c));
            helper(res, index + 1, sb, S);
            sb.setLength(sb.length() - 1);
        } else {
            sb.append(c);
            helper(res, index + 1, sb, S);
            sb.setLength(sb.length() - 1);
        }
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array