2014-02-07 73 views
1

我在這個格式的字符串: a,b,c[a,b,c[a]],d分裂遞歸組

什麼(到底),我想結束了,是

a 
b 
c.a 
c.b 
c.c.a 
d 

對如何處理這個任務的任何建議?

+4

可能更容易(更可能是可能的),而正則表達式。 – Jerry

+5

這不是一個正則表達式的東西。解析它自己。 –

+0

我想是的。謝謝。 – mortenoh

回答

1

這是一個使用堆棧的可能解決方案。 (實施Avlin鋪位的評論。)

public static Iterable<String> split(String s) { 
    List<String> result = new LinkedList<String>(); 
    Stack<String> stack = new Stack<String>(); 
    Pattern pattern = Pattern.compile("[,\\[\\]]|.+?"); 
    Matcher matcher = pattern.matcher(s); 

    stack.push(""); 
    while (matcher.find()) { 
     String token = matcher.group(); 
     if (token.equals("[")) { 
      stack.push(""); 
     } else if (token.equals("]")) { 
      if (! stack.peek().isEmpty()) 
       result.add(join(".", stack)); 
      stack.pop(); 
      stack.pop(); 
      stack.push(""); 
     } else if (token.equals(",")) { 
      if (! stack.peek().isEmpty()) 
       result.add(join(".", stack)); 
     } else { 
      stack.pop(); 
      stack.push(token); 
     } 
    } 
    if (! (stack.isEmpty() || stack.peek().isEmpty())) 
     result.add(join(".", stack)); 
    return result; 
} 

public static String join(String sep, Iterable<String> it) { 
    // Return it[0] + sep + it[1] + sep + .... + it[lastIndex] 
    String joined = ""; 
    boolean first = true; 

    for (String s : it) { 
     if (first) 
      first = false; 
     else 
      joined += sep; 
     joined += s; 
    } 
    return joined; 
} 

實例應用:

String text = "a,b,c[a,b,c[a]],d"; 
for (String s : split(text)) 
    System.out.println(s); 

Demo run

Same solution in PythonRecursive solution in Python