[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...
    又是夜半驚坐起閱讀 9,939評論 0 23
  • 昨晚失眠睜著眼睛到3點~ 朋友圈刷到無可再刷, 公眾號訂閱更新文章全部讀完, 已經很累了就是睡不著, 在床上默默的...
    愛偷懶的喵主閱讀 458評論 2 1
  • “聽過很多道理,卻依然過不好這一生。”這是韓寒導演的《后會無期》影片的一句原話。 自認為道理懂很多,能給別人巴拉巴...
    鄭珍容閱讀 278評論 1 1
  • 題記:走過人生一程,細聽自己的腳步聲,然后把它記錄下來,告訴自己,這個世界,我曾經來過…… 迷戀工筆畫有二月余,愛...
    紫雨true閱讀 216評論 5 7
  • 今天的故事,關于CL。他可以算是我高中時期最重要的人之一,難得的好哥們,長得一副鬼精的樣子,數理化都過得去。于是,...
    高Rachel閱讀 383評論 0 0