Question:

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.

 

Analysis:

问题描述:给出一个字符串,包含'(', ')', '{', '}', '[' and ']'确定它是否是有效地匹配括号。

思路:一看到括号匹配问题肯定想到用栈。遇到左括号就进栈;遇到右括号若栈顶元素与之匹配则POP出栈顶元素,若不匹配则返回false。

注意特殊情况:如"{}[]()", 或者“{[}]”, 或者“{{}}{{”等情况。

 

Answer:

public class Solution {
    public boolean isValid(String s) {
        char[] ch = s.toCharArray();
        int n = ch.length;
        if(ch.length == 0 || ch.length % 2 != 0)
            return false;
        if(ch[0] == '}' || ch[0] == ']' || ch[0] == ')')
            return false;
        Stack<Character> st = new Stack<Character>();
        st.add(ch[0]);
        int i = 1;
        while(!st.isEmpty() && i < n) {
            if(ch[i] == '{' || ch[i] == '[' || ch[i] == '(') {
                st.add(ch[i]);
                i++;
            } else {
                if(st.isEmpty())
                    return false;
                char c = st.pop();
                if(c == '{' && ch[i] != '}' || c == '[' && ch[i] != ']'
                        || c == '(' && ch[i] != ')')
                    return false;
                i++;
                if(i < n && (ch[i] == '{' || ch[i] == '[' || ch[i] == '(')) {
                    st.add(ch[i]);
                    i++;
                } 
            }
        }
        System.out.println(i +" " +st.size());
        if(!st.isEmpty() || i < n - 1)
            return false;
        
        return true;
    }
    
}

 

相关文章:

  • 2021-06-22
  • 2021-12-23
  • 2021-08-19
  • 2022-01-30
  • 2022-02-17
  • 2022-03-08
  • 2021-10-07
猜你喜欢
  • 2021-09-11
  • 2022-02-17
  • 2022-03-04
  • 2021-10-19
  • 2021-05-31
  • 2021-07-08
  • 2021-06-18
相关资源
相似解决方案