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.

思路:用dfs,括号里面的,收集起来,然后for循环,这题要学会用Character.isLetter,用来跳过逗号;核心思想就是遇见括号,收集起来for循环,取一个,然后index继续往前走,直到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);
        }
    }
}
发布了562 篇原创文章 · 获赞 13 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/104002281