20. Valid Parentheses (Easy)

来源:互联网 发布:广州恒大淘宝队微博 编辑:程序博客网 时间:2024/06/06 00:41

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.

括号匹配,用到了数据结构中的栈,这里用Java完成代码:

Solution:

Java:

import java.util.Stack;public class Solution {    public boolean match(char c1, char c2) {        if(c1 == '(' && c2 == ')' || c1 == ')' && c2 == '(') {            return true;        }        if(c1 == '{' && c2 == '}' || c1 == '}' && c2 == '{') {            return true;        }        if(c1 == '[' && c2 == ']' || c1 == ']' && c2 == '[') {            return true;        }        return false;    }    public boolean isValid(String s) {        Stack<Character> stack = new Stack<>();        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if(c == '(' || c == '{' || c == '[') {                stack.push(c);            } else {                if(stack.isEmpty()) return false; // 字符串开始就是右括号                char cc = stack.pop();                if(!match(c, cc)) {                    return false;                }            }        }        return stack.isEmpty();    }    public void test() {        System.out.println(isValid("]"));    }    public static void main(String[] args) {        new Solution().test();    }}
0 0
原创粉丝点击