首页 > 代码库 > leetcode 20. Valid Parentheses

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

 

leetcode 20. Valid Parentheses