2019年11月26日午前11時05分10秒
- 1096ブレース展開II
問題の説明:
問題解決:
クラシック文字列のスケーリングの問題。
一般に、この問題の2つのソリューションがあり、それは1つが、再帰的に使用され、スタックを使用することです。事実は、再帰を使用してみてください、時間効率と読みやすさの面で再帰的な手順を使用して、このような話題がスタックよりもはるかに高いことを証明しています。
この質問は非常に良い説明ビデオを持っています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; }