括号匹配

来源:互联网 发布:全面预算软件 编辑:程序博客网 时间:2024/05/17 03:27

输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有”[“,”]”,”(“,”)”四种字符。

//-------------------javapackage pack;import java.util.Scanner;import java.util.Stack;public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        String s = sc.nextLine();        //String s = "[havf9]";        if(ismatch(s))            System.out.println("match");        else            System.out.println("not match");        }    private static boolean ismatch(String s) {        Stack<Character> sk = new Stack<Character>();        if(s.isEmpty())            return true;        for(int i = 0; i<s.length(); i++) {            if(s.charAt(i) == '(') {                sk.push('(');            }            if(s.charAt(i) == ')') {                if(sk.pop() == '(')                     continue;                else                     return false;            }            if(s.charAt(i) == '[') {                sk.push('[');            }            if(s.charAt(i) == ']') {                if(sk.pop() == '[')                     continue;                else                     return false;            }        }        return true;    }}
//--------------------c++bool ismatch(string s) {    stack<char> sk;    if (s.empty())        return true;    for (int i = 0; i < s.length; i++) {        if (s.at(i) == '(')            sk.push('(');        if (s.at(i) == ')') {            if (sk.pop == '(')                continue;            else                return false;        }        if (s.at(i) == '[') {            sk.push('[');        }        if (s.at(i) == ']') {            if (sk.pop == '[')                continue;            else                return false;        }    }    return true;}
0 0
原创粉丝点击