Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Parse and flatten string
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; //1、有点像欧洲那旮瘩的白人哥,“f{a,b}c{d,e}” => facd face fbcd fbce。要用他的api。followup是f{a{b},c},有嵌套 class Rextester { public static void main(String args[]) { Solution sol = new Solution(); System.out.println(sol.expand("f{a,b}c{d,e}x").toString()); System.out.println(sol.expandHier("f{a{b,c},d}").toString()); System.out.println(sol.expandHier("f{{b,c},d}x").toString()); System.out.println(sol.expandHier("f{a{b,f{a,b}c{d,e}x},d}x").toString()); } } class Solution { public List<String> expand(String s) { List<String> res = new ArrayList<>(); if (s.length() == 0) return res; StringBuilder sb = new StringBuilder(); res.add(""); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != '{') sb.append(s.charAt(i)); else { List<String> tmp = new ArrayList<>(); List<String> tokens = new ArrayList<>(); int j = findMatchAndSplit(s, i, tokens, '{', '}', ','); for (String token: tokens) for (String prefix: res) tmp.add(prefix + sb + token); i = j; res = tmp; sb.setLength(0); } } if (sb.length() > 0) { List<String> tmp = new ArrayList<>(); for (String prefix: res) tmp.add(prefix + sb); res = tmp; } return res; } public int findMatchAndSplit(String s, int fromIndex, List<String> tokens, char open, char close, char split) { int count = 0; for (int i = fromIndex, j = fromIndex + 1; i < s.length(); i++) { if (s.charAt(i) == open) count++; else if (s.charAt(i) == close) { count--; if (count == 0) { tokens.add(s.substring(j, i)); return i; } } else if (s.charAt(i) == split && count == 1) { tokens.add(s.substring(j, i)); j = i + 1; } } return -1; } public List<String> expandHier(String s) { List<String> res = new ArrayList<>(); for (String ans: expand(s)) { if (ans.indexOf('{') == -1) res.add(ans); else res.addAll(expandHier(ans)); } return res; } }
run
|
edit
|
history
|
help
0
patterns
First Interview question - Java
3rd
3.A
Rextester.java
Remove duplicates in string
Java Object Info
cuboid volume
Count and Say
jb14 isEven Links