LeetCode解题报告--Valid Parentheses

来源:互联网 发布:python 2.7 3.5 区别 编辑:程序博客网 时间:2024/06/09 18:57

**题目:**Valid Parentheses

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.

分析:题意要求判断输入的符号(”()”,”{}”,”[]”)字符串是否是成对匹配。
改题用栈(stack)是最简单直接的解法,直接调用java内部stack类包。
1)新建一个栈,将输入的字符串中的“(”,“{”,“[”压入栈,
2)当遇到字符串中”)”或”}”或”]”,与栈最后一个元素进行判断,如如果当前的字符是”)”,则需要判断此时的栈顶元素是否为”)”,如果不是则直接返回false,结束程序;如果是则将栈顶元素pop,
3)循环执行2)中步骤,直至字符串遍历完成。

Java Accepted代码:

public class Solution {    public boolean isValid(String s) {        if (s.length() % 2 != 0) {            return false;        }        Stack<Character> string = new Stack<Character>();        char ch;        for (int i = 0; i < s.length(); i++) {            if (s.charAt(i) == '[' || s.charAt(i) == '(' || s.charAt(i) == '{') {                string.push(s.charAt(i));                //System.out.println(string);            } else {                if (string.isEmpty()){                    return false;                }                else {                    ch = s.charAt(i);                    switch (ch) {                    case ']':                        if (string.pop() != '[')                            return false;                        break;                    case ')':                        if (string.pop() != '(')                            return false;                        break;                    case '}':                        if (string.pop() != '{')                            return false;                        break;                    }                }            }        }        if(string.isEmpty()){            return true;        }else{            return false;        }    }}

与此相关的内容在之前的博客《基于链表实现Java 自定义Stack栈》

相关代码放在个人github:https://github.com/gannyee/LeetCode/

0 0
原创粉丝点击