Leetcode20 括号匹配

有效括号字符串验证

1.使用栈解决


#include <iostream>
#include <stack>
using namespace std;

class Solution
{
public:
    bool isValid(string s)
    {
        stack<char> stack;//定义一个栈
        int strSize = s.size();//字符串长度
        if(strSize % 2 == 1){//
            return false;
        }
        for (char tmpChar : s)
        {
            char popChar;//= ' ';
            switch (tmpChar)
            {
                //如果是(,[,{,就压入栈中
                case '(':
                case '[':
                case '{':
                    stack.push(tmpChar);
                    break;
                case ')':
                    //注意栈为空的情况
                    if (stack.empty())
                    {
                        return false;
                    }
                    popChar = stack.top();//取栈顶元素
                    stack.pop();
                    if (popChar != '(')
                    {
                        return false;
                    }
                    break;
                case ']':
                    if (stack.empty())
                    {
                        return false;
                    }
                    popChar = stack.top();
                    stack.pop();
                    if (popChar != '[')
                    {
                        return false;
                    }
                    break;
                case '}':
                    if (stack.empty())
                    {
                        return false;
                    }
                    popChar = stack.top();
                    stack.pop();
                    if (popChar != '{')
                    {
                        return false;
                    }
                    break;
                default:
                    return false;

            }
        }
        if (stack.empty())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
};
int main(){
    Solution a;
    bool flag=a.isValid("((");
    cout<<flag<<endl;
}
 public static boolean isValid(String s){
        // 判断符号的长度是否为奇数,奇数直接返回false
        if((s.length() & 1) == 1){
            return false;
        }

        Stack<Character> stack = new Stack<>();//java
        for(int i = 0; i < s.length(); i++){//先将整个字符串入栈
            if(stack.isEmpty()){
                stack.push(s.charAt(i));
            } else {
                // 只需处理右括号,其余情况压入栈即可
                switch (s.charAt(i)){
                    case ')': {
                        if(stack.pop() != '('){
                            return false;
                        }
                        break;
                    }
                    case ']': {
                        if(stack.pop() != '['){
                            return false;
                        }
                        break;
                    }
                    case '}': {
                        if(stack.pop() != '{'){
                            return false;
                        }
                        break;
                    }
                    default: stack.push(s.charAt(i));
                }
            }
        }
        // 如果栈不为空,说明括号有重复单边括号,返回false
        if(!stack.isEmpty())
            return false;
        return true;
    }

2.使用map
注意键值对的顺序

class Solution {
public:
    bool isValid(string s) {
        if (s.length() % 2 != 0) return false;//一但是奇数说明不是有效的括号
        //unordered_map<char, char> wordbook;//建立哈希表
        unordered_map<char, char> wordbook;//建立哈希表
        /*wordbook.insert(map<char, char>::value_type(')', '('));
        wordbook.insert(map<char, char>::value_type(']', '['));
        wordbook.insert(map<char, char>::value_type('}', '{'));
         */
        wordbook.insert({')','('})//必须先写)后写(,键值对根据健)去匹配(
        wordbook.insert({']','['});
        wordbook.insert({'}','{'});

        stack<char> mystack;//建立栈
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == '[' || s[i] == '{' || s[i] == '(')//匹配到左括号
                mystack.push(s[i]);//放入栈中
            else if (s[i] == ']' || s[i] == '}' || s[i] == ')')//匹配到右括号
            {
                if (mystack.empty()) return false;
                //匹配到右括号,栈中应该存在左括号。否则就是无效的括号
                if (wordbook[s[i]] == mystack.top())//与栈顶元素进行匹配
                {
                    mystack.pop();//匹配成功删除栈顶元素
                    continue;
                } else return false;
            }
        }
        if (mystack.empty()) return true;//有效的括号到最后检测结束栈中应没有元素
        else return false;
    }
};
class Solution {

  // Hash table that takes care of the mappings.
  private HashMap<Character, Character> mappings;//hashmap

  // Initialize hash map with mappings. This simply makes the code easier to read.
  public Solution() {
    this.mappings = new HashMap<Character, Character>();
    this.mappings.put(')', '(');//put不是insert
    this.mappings.put('}', '{');
    this.mappings.put(']', '[');
  }

  public boolean isValid(String s) {

    // Initialize a stack to be used in the algorithm.
    Stack<Character> stack = new Stack<Character>();

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

      // If the current character is a closing bracket.
      if (this.mappings.containsKey(c)) {

        // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
        char topElement = stack.empty() ? '#' : stack.pop();

        // If the mapping for this bracket doesn't match the stack's top element, return false.
        if (topElement != this.mappings.get(c)) {
          return false;
        }
      } else {
        // If it was an opening bracket, push to the stack.
        stack.push(c);
      }
    }

    // If the stack still contains elements, then it is an invalid expression.
    return stack.isEmpty();
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值