[英]How to extract content from curly brackets to arraylists
我需要像這樣提取大括號之間的字符串,例如{3{4 5}6}
然后
我試過刪除大括號,但只有當我只有一對大括號時才能做到; 當我有類似上面例子的東西時,它只是把它放到一個列表中,而列表 B 是空的。
為了將列表與您擁有的列表的大括號表示法分開,您可以遵循一個簡單的基於堆棧的算法來生成最終的列表列表。
請注意,當您輸入如下字符串時,
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}"
然后你從第一個字符開始遍歷,你可以看到每當遇到像'{'這樣的左花括號時,你必須開始一個新列表。 類似地,當您遇到右大括號 '}' 時,您必須關閉您最近正在構建的先前打開的列表。
例如,算法將運行如下:
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}" | |
^ | |
| [] | //push new list because you found a '{'
stack
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}" | |
^ | |
| [3] | //push 3 to topmost list
stack
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}" | |
^ | [] |
| [3] | //push new list because you found a '{'
stack
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}" | |
^ | [4] |
| [3] | // push 4 to topmost list
stack
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}" | |
^ | [4 5] |
| [3] | //push 5 to topmost list
stack
"{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}" | |
^ | | //pop [4 5] and store it
| [3] | //because you found a '}'
stack
... and so on
下面是算法的簡單實現。 請注意,它僅適用於所有括號都平衡的輸入:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
String input = "{3 {4 5} 6 { 5 6 7 8 9} 1 1 1 1}";
ArrayList<ArrayList<Integer>> result = getLists(input);
for (List<Integer> l1 : result) {
for (Integer n : l1) {
System.out.print(n + " ");
}
System.out.println();
}
}
public static ArrayList<ArrayList<Integer>> getLists(String s){
s = s.replaceAll(" ", "");
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayDeque<ArrayList<Integer>> stack = new ArrayDeque<ArrayList<Integer>>();
for(int i=0;i<s.length();i++){
if(s.charAt(i) == '{'){
//add new list to stack
ArrayList<Integer> list = new ArrayList<Integer>();
stack.push(list);
}
else if(s.charAt(i) == '}'){
//pop topmost list from stack and add to result
result.add(stack.pop());
}else{
stack.peek().add(Character.getNumericValue(s.charAt(i)));
}
}
return result;
}
}
上述算法的輸出:
4 5
5 6 7 8 9
3 6 1 1 1 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.