leetcode 20. Valid Parentheses

  栈的相关操作。

  

public class Solution {
   public boolean isValid(String s) {
        
        if(s == "") return true;
        
        Stack<Character> st = new Stack<Character>();
        st.push(s.charAt(0));
        
        for(int i = 1; i < s.length(); i++){
            
            if(!st.empty() && judge(st.peek(),s.charAt(i))){
                st.pop();//peek() 查看栈顶元素,但不取出,pop()取出栈顶元素
            }
            else{
                st.push(s.charAt(i));
            }
        }
        
        if(st.empty()) 
            return true;
        return false;
        
        
    }
    private boolean judge(char a, char b) {
        
        if(a == '(' && b == ')' || a == '[' && b == ']' || a == '{' && b == '}')
            return true;
        return false;
    }
}
View Code
原文地址:https://www.cnblogs.com/zyqBlog/p/5990011.html