匹配括号
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Stack; public class Stackmatch { public static void main(String[] args) { //输入 int keyin=6; String source[]={"(","(","(",")","(","(",")",")",")",")"}; // 1 2 3 4 5 6 7 8 9 10 //计算 StringBuilder result=new StringBuilder(); int intnum=keyin-1; Stack<String> s=new Stack<String>(); // ")" right to left String flag=source[intnum]; int start=intnum; if(flag.equals("(")){ }else{ start=source.length-intnum-1; } String sourceb[]=source.clone(); List<String> l=Arrays.asList(source); if(flag.equals(")")){ Collections.reverse(Arrays.asList(sourceb)); }else{ Collections.reverse(l); } s.addAll(l); boolean startscan=false; boolean end=false; int index=0; int mark=1; while(!end){ String tmp=s.pop(); if(index==start){ //System.out.println("start:"+keyin); result.append("start:"+keyin); startscan=true; index++; continue; } if(startscan){ if(tmp.equals(sourceb[start])){ mark++; }else{ mark--; } if(mark==0) { end=true; if(flag.equals(")")){ // System.out.println("end:"+(source.length-index-1+1)); result.append(" end:"+(source.length-index-1+1)); }else{ //System.out.println("end:"+(index+1)); result.append(" end:"+(index+1)); } break; } } index++; } System.out.println(result); } }