Leetcode014--括号验证匹配

一、原题



Given a string containing just the characters '(',  ')',  '{',  '}',  '[' and  ']', determine if the input string is valid. 
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not. 



二、中文



给定一个只包含 '(',  ')',  '{',  '}',  '[' and  ']', 的字符串,验证它是否是有效的。括号必须配对,并且要以正确的顺序。 



三、举例



比如给出字符串{[(sdffsf)]},我们返回true



四、思路



建立以个栈,遍历每个元素,当为左括号的时候入栈,为右括号的时候,进行判断和出栈,其他的时候就break,遍历完之后看下栈中是否为空就可以了。



五、程序


package LeetCode;

import java.util.Stack;

public class Leetcode015 {
	
	public static void main(String args[]){
		System.out.println(isValid("{([]){())(()}}"));
		System.out.println(isValid("({qr[wafd]})"));
	}

    public static boolean isValid(String s) {

    	Stack stack = new Stack();
        int index = 0;
        Character top;
        while (index < s.length()) {
            Character c = s.charAt(index);
            //当为这三个符号的时候就
            switch (c) {
                case '(':
                case '[':
                case '{':
                    stack.push(c);
                    break;
                case ')':

                    if (stack.isEmpty()) {
                        return false;
                    }

                    top = stack.lastElement();
                    if (top == '(') {
                        stack.pop();
                    } else if (top == '[' || top == '{') {
                        return false;
                    } else {
                        stack.push(c);
                    }
                    break;
                case ']':

                    if (stack.isEmpty()) {
                        return false;
                    }

                    top = stack.lastElement();
                    if (top == '[') {
                        stack.pop();
                    } else if (top == '(' || top == '{') {
                        return false;
                    } else {
                        stack.push(c);
                    }
                    break;
                case '}':

                    if (stack.isEmpty()) {
                        return false;
                    }

                    top = stack.lastElement();
                    if (top == '{') {
                        stack.pop();
                    } else if (top == '[' || top == '(') {
                        return false;
                    } else {
                        stack.push(c);
                    }
                    break;
                    //其他的情况也就是当时一下字母的时候就跳过
                default:
                    break;
            }

            index++;
        }

        return stack.isEmpty();
    }

}
---------------------output----------------------
false
true



你可能感兴趣的:(【LeetCode】)