您的位置:首页 > 编程语言 > Java开发

括号匹配算法

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 括号匹配