JAVA栈实例—括号匹配
1 import java.util.Stack; 2 3 public class test { 4 public static void main(String[] args){ 5 System.out.print(isStringBalanced("asdasd)d")); 6 } 7 8 public static boolean isStringBalanced(String string){ 9 final char openrb = '('; //定义常量 10 final char closerb = ')'; 11 Stack<Character> s = new Stack<Character>(); //新建栈 12 for (int i=0;i<string.length();i++){ 13 if (string.charAt(i) == openrb){ 14 s.push(openrb); //压入占顶 15 }else if(string.charAt(i) == closerb){ 16 if (s.empty()){ //是否为空 17 s.push(closerb); 18 }else if ((char)s.peek() == openrb){ //查看栈顶元素,但是不弹出 19 s.pop(); //弹出栈顶元素 20 }else{ 21 s.push(closerb); 22 } 23 } 24 25 } 26 return s.empty(); 27 } 28 }