Brace Expansion

A string S represents a list of words.

Each letter in the word has 1 or more options.  If there is one option, the letter is represented as is.  If there is more than one option, then curly braces delimit the options.  For example, "{a,b,c}" represents options ["a", "b", "c"].

For example, "{a,b,c}d{e,f}" represents the list ["ade", "adf", "bde", "bdf", "cde", "cdf"].

Return all words that can be formed in this manner, in lexicographical order.

Ideas: The dfs, brackets, and collected, then the for loop, this question must learn Character.isLetter, used to skip a comma; core idea is to meet brackets, collected for recycling, take a, and then continue to move forward index go until the index == s.length ();

class Solution {
    public String[] expand(String S) {
        if(S == null || S.length() == 0) {
            return new String[0];
        }
        
        List<String> list = new ArrayList<String>();
        StringBuilder sb = new StringBuilder();
        dfs(S, list, 0, sb);
        return convert(list);
    }
    
    private String[] convert(List<String> list) {
        String[] res = new String[list.size()];
        for(int i = 0;  i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
    
    private void dfs(String S, List<String> list, int index, StringBuilder sb) {
        if(index == S.length()){
            if(sb.length() > 0) {
                list.add(new String(sb.toString()));
            }
            return;
        }
        
        char c = S.charAt(index);
        if(c == '{') {
            List<Character> chars = new ArrayList<Character>();
            int endindex = index+1;
            while(endindex < S.length() && S.charAt(endindex) != '}'){
                if(Character.isLetter(S.charAt(endindex))) {
                    chars.add(S.charAt(endindex));
                }
                endindex++;
            }
            
            Collections.sort(chars);
            for(Character a : chars) {
                sb.append(a);
                dfs(S, list, endindex+1, sb);
                sb.deleteCharAt(sb.length() -1);
            }
        } else if(Character.isLetter(c)) {
            sb.append(c);
            dfs(S, list, index+1, sb);
            sb.deleteCharAt(sb.length() -1);
        }
    }
}

 

Published 562 original articles · won praise 13 · views 170 000 +

Guess you like

Origin blog.csdn.net/u013325815/article/details/104002281