美文网首页
LeetCode(Number 20)

LeetCode(Number 20)

作者: Chris_PaulCP3 | 来源:发表于2019-01-04 20:31 被阅读0次

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

这道题不是很理解为什么这样做,Mark一下

public class Solution {
    public static boolean isValid(String s) {
        if(s == null || s.length() == 0 )
            return true;
        Stack<Character> st = new Stack<Character>();
        for(char ch:s.toCharArray())
        {
            if (ch == '(')
                st.push(')');
            else if (ch == '{')
                st.push('}');
            else if (ch == '[')
                st.push(']');
            else if (st.isEmpty() || st.pop() != ch)
                return false;
        }
        return st.empty();
    }
    public static void main(String[] args)
    {
        String s="()";
        System.out.println(isValid(s));
        
    }
   
}

相关文章

网友评论

      本文标题:LeetCode(Number 20)

      本文链接:https://www.haomeiwen.com/subject/njakrqtx.html