2019-11-26 11:05:10
- 1096. Brace Expansion II
Problem Description:
Problem Solving :
Classic string scaling issues.
In general there are two solutions of this problem, it is to use a stack, one is the use of recursive. Facts have proved that such a topic using recursive procedures in terms of time efficiency and readability is much higher than the stack, try using recursive.
This question has a very good explanation video: https://www.youtube.com/watch?v=blXuT7DOMwU
public List<String> braceExpansionII(String expression) { List<String> res = new ArrayList<>(); if (expression.length() <= 1) { res.add(expression); return res; } if (expression.charAt(0) == '{') { int cnt = 0; int idx = 0; for (; idx < expression.length(); idx++) { if (expression.charAt(idx) == '{') cnt += 1; if (expression.charAt(idx) == '}') cnt -= 1; if (cnt == 0) break; } List<String> strs = helper(expression.substring(1, idx)); HashSet<String> set = new HashSet<>(); for (String str : strs) { List<String> tmp = braceExpansionII(str); set.addAll(tmp); } List<String> rest = braceExpansionII(expression.substring(idx + 1)); for (String str1 : set) { for (String str2 : rest) { res.add(str1 + str2); } } } else { String prev = expression.charAt(0) + ""; int idx = 0; List<String> rest = braceExpansionII(expression.substring(1)); for (String s : rest) res.add(prev + s); } Collections.sort(res); return res; } public List<String> helper(String s) { List<String> res = new ArrayList<>(); int cnt = 0; int i = 0; for (int j = 0; j < s.length(); j++) { if (s.charAt(j) == ',') { if (cnt == 0) { res.add(s.substring(i, j)); i = j + 1; } } else if (s.charAt(j) == '{') cnt += 1; else if (s.charAt(j) == '}') cnt -= 1; } res.add(s.substring(i)); return res; }