LeetCode 150 classic interview questions -- effective parentheses (simple)

1. Topic

Given a  string that contains only '(', ')', '{', '}', '[', determine whether the string is valid.']'s

A valid string must satisfy:

  1. An opening parenthesis must be closed with a closing parenthesis of the same type.
  2. Opening parentheses must be closed in the correct order.
  3. Each closing parenthesis has a corresponding opening parenthesis of the same type.

2. Examples

Example 1:

Input: s = "()"
Output: true

 Example 2:

Input: s = "()[]{}"
Output: true

 Example 3:

Input: s = "(]"
Output: false

hint:

  • 1 <= s.length <= 104
  • s'()[]{}'Consists of parentheses only

 3. Ideas

First of all, you need to find the law. First, if the number of the string is odd, it is absolutely invalid. And you need to use the stack to judge. When you encounter a right parenthesis, compare it with the element on the top of the stack. If it is a matching left parenthesis, pop it out of the stack. If there is a mismatch then

4. Code

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        //        如果个数是奇数则绝对有问题
        if (s.length()%2==1){
            return false;
        }
        Map<Character,Character> map = new HashMap<>();
        map.put('}','{');
        map.put(')','(');
        map.put(']','[');

//       右括号无法存放进入stack中
        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(stack.isEmpty()){
                   return false;
               }
               if (stack.peek() == map.get(s.charAt(i))){
                   stack.pop();
               }else {
                   return false;
               }
           }
        }
        if (!stack.isEmpty()){
           return false;
        }
        return true;
    }
}

Time complexity O(n), space complexity O(1)


Will it? Try to challenge the next question! ♪(^∀^●)ノシ(●´∀`)♪

 

LeetCode 150 interview classic questions -- circular linked list (simple)_Alphamilk's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/dogxixi/article/details/132304902