括号匹配算法
2013-07-29 11:23
337 查看
括号匹配算法-java实现
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; public class BracketsMatch { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please input text:"); String input = br.readLine(); if(isMatch(input))System.out.println("匹配!"); else System.out.println("不匹配!"); } public static boolean isMatch(String input) { Stack<Character> st = new Stack<Character>(); char temp; for (int i = 0; i < input.length(); i++) { temp = input.charAt(i); if (temp == '(')st.push(')'); if (temp == '{')st.push('}'); if (temp == '[')st.push(']'); if (temp == '<')st.push('>'); if (temp == ')' || temp == '>' || temp == '}' || temp == ']') { if (temp != st.pop()) return false; } } if (st.isEmpty() == true) return true; else return false; } }