LeetCode简单题:20. 有效的括号(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/valid-parentheses/
要点:栈

Python,C++,Java用的方法相同,遍历字符串,对每个字符如果是左括号直接加入栈,如果是右括号则要取栈顶元素比较是否是匹配括号

二.Python实现

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []

        hashmap = {")": "(", "}": "{", "]": "["}

        for char in s:

            if char in hashmap:
                top_element = stack.pop() if stack else '#'
                if hashmap[char] != top_element:
                    return False
            else:
                stack.append(char)

        return not stack

三.C++实现

class Solution {
public:
    bool isValid(string s) {
        
        stack a;
        if(s.length()==0) return true;
        
        for(int i=0;i

四.java实现

class Solution {

  private HashMap mappings;

  public Solution() {
    this.mappings = new HashMap();
    this.mappings.put(')', '(');
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    Stack stack = new Stack();

    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);

      if (this.mappings.containsKey(c)) {

        char topElement = stack.empty() ? '#' : stack.pop();

        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } 
      else {
        stack.push(c);
      }
    }

    return stack.isEmpty();
  }
}

你可能感兴趣的:(LeetCode简单题:20. 有效的括号(Python,C++,Java))