[LeetCode] 20. Valid Parentheses

</br>


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.


</br>

Solution

We should know that if the string is valid parentheses, the string has to have pairing characters and should close in the correct order.

In this way, the most inner brackets and the first close bracket in the entire string should contain no other brackets. And this can be our way in.

By applying stack, we can push any open parentheses onto stack, and when we encounter the first close parentheses, it has to match the character that pops out the stack, otherwise this string is no valid parentheses.

Additionally, the code is using stack.peek() function to find out the current value of the stack without removing it.

The code is shown as below.

Java

public class Solution {
    public boolean isValid(String s) {
        
        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) == ')' && !stack.empty() && stack.peek() == '(')
                stack.pop();
            else if(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[')
                stack.pop();
            else if(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{')
                stack.pop();
            else
                return false;
        }
        
        return stack.empty();
    }
}

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,450评论 0 23
  • 昨晚失眠睁着眼睛到3点~ 朋友圈刷到无可再刷, 公众号订阅更新文章全部读完, 已经很累了就是睡不着, 在床上默默的...
    爱偷懒的喵主阅读 3,211评论 2 1
  • “听过很多道理,却依然过不好这一生。”这是韩寒导演的《后会无期》影片的一句原话。 自认为道理懂很多,能给别人巴拉巴...
    郑珍容阅读 1,846评论 1 1
  • 题记:走过人生一程,细听自己的脚步声,然后把它记录下来,告诉自己,这个世界,我曾经来过…… 迷恋工笔画有二月余,爱...
    紫雨true阅读 1,449评论 5 7
  • 今天的故事,关于CL。他可以算是我高中时期最重要的人之一,难得的好哥们,长得一副鬼精的样子,数理化都过得去。于是,...
    高Rachel阅读 2,885评论 0 0