leetcode第20题——*Valid Parentheses

来源:互联网 发布:mac怎么给手机换铃声 编辑:程序博客网 时间:2024/06/05 05:47

题目

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.


思路

巧妙利用栈后进先出的特点,存储括号的前部'{','['或'('。每当遍历到字符串中有括号的后部时,取出栈顶元素并判断栈顶元素是否为对应的前部,例如遍历到'{'栈顶应该对应'}',若有对应前部则继续遍历,若没有或栈为空则返回False。遍历完后判断栈是否为空,若最后栈为空则代表括号能一一对应上,返回True;若最后栈不为空说明有些括号的前部没有相对应位置的后部,应该返回False。
PS:据我所知Python不像Java那样有自带的Stack类,使用Python时可以自己定义一个Stack,按本题需求,在类里面定义一些基本的方法如push,pop,isEmpty即可。

代码

Python

class Stack(object):    def __init__(self):        self.stack = []        self.top = -1            def push(self,data):        self.stack.append(data)        self.top += 1            def pop(self):        data = self.stack[-1]        self.top -= 1        del self.stack[-1]        return data            def isEmpty(self):        if(self.top == -1):            return True        else:            return Falseclass Solution(object):    def isValid(self, s):        """        :type s: str        :rtype: bool        """        if(s==None or len(s)==0):            return True        if(len(s)%2 != 0):            return False        stk = Stack()                for i in xrange(0,len(s)):            if(s[i] == '{' or s[i] == '[' or s[i] == '('):                stk.push(s[i])            elif(s[i] == '}'):                if(not stk.isEmpty()):                    if(stk.pop() != '{'):                        return False                else:                    return False            elif(s[i] == ']'):                if(not stk.isEmpty()):                    if(stk.pop() != '['):                        return False                else:                    return False            elif(s[i] == ')'):                if(not stk.isEmpty()):                    if(stk.pop() != '('):                        return False                else:                    return False                if(stk.isEmpty()):            return True        return False


Java

public class Solution {    public boolean isValid(String s) {        if(s == null || s.isEmpty()){            return true;        }        if (s.length() % 2 != 0){            return false;        }        Stack<Character> stack = new Stack<Character>();        for (int i = 0 ; i < s.length(); i++){            if (s.charAt(i) == '{' || s.charAt(i) == '(' || s.charAt(i) == '['){                stack.push(s.charAt(i));            }            else if (s.charAt(i) == '}'){                if(!stack.isEmpty()){                    if (stack.pop() != '{'){                        return false;                    }                }                else {                    return false;                }            }            else if (s.charAt(i) == ')'){                if(!stack.isEmpty()){                    if (stack.pop() != '('){                        return false;                    }                }                else {                    return false;                }            }            else if (s.charAt(i) == ']'){                if(!stack.isEmpty()){                    if (stack.pop() != '['){                        return false;                    }                }                else {                    return false;                }            }        }        if(stack.isEmpty()){            return true;        }        return false;    }}


1 0
原创粉丝点击