通过栈(先进后出)思想把{}{}之间的数据放到集合中

public void static main(String[] args){
     
String text ="{a:A,b:B}|{c:C,d:D};{e:E,f:F} {h:H,q:Q}";
List<String> List = new ArrayList<String>();
StringBuffer sb = new StringBuffer("");
//申明一个stack
Stack<Character> stack = new Stack<Character>();
 for(int i=0;i<text.length();i++){
     
    char ch =text.charAt(i);
    if(ch == '{'){
     
       sb.append(ch);
      stack.push(ch);//入栈
    }else{
     
      if(stack.empty()){
     
         continue;
      }
       sb.append(ch);
       //stack.peek() 栈顶
       if(ch == '}' && stack.peek() == '{' && stack.size()>=1){
     
			if(stack.size() == 1){
     
				list.add(sb.toString());
				sb.setLength(0);//清理比较高效
			}
			stack.pop();//出栈
		}
    }
 }
 //如果为空,则说明栈中不存在元素,就表示全部匹配成功
 if(stack.empty()){
     
   System.out.print(list.toString());
 }
}

输出结果
[{a:A,b:B},{c:C,d:D},{e:E,f:F},{h:H,q:Q}]

你可能感兴趣的:(栈,数据结构,java)