头图

title: Daily Practice (36): Valid Parentheses

categories:[Swords offer]

tags:[Daily practice]

date: 2022/03/15


Exercise of the Day (36): Effective Brackets

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

A valid string must satisfy:

Opening parentheses must be closed with closing parentheses of the same type.

Left parentheses must be closed in the correct order.

Example 1:

Input: s = "()"

output: true

Example 2:

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

output: true

Example 3:

Input: s = "(]"

output: false

Example 4:

Input: s = "([)]"

output: false

Example 5:

Input: s = "{[]}"

output: true

hint:

1 <= s.length <= 104

s consists only of parentheses '()[]{}'

Source: LeetCode

Links: https://leetcode-cn.com/problems/valid-parentheses

Method 1: stack + hash table

Thought analysis

  1. The length of a valid bracket string, must be an even number!
  2. Before the closing parenthesis, it must be the corresponding opening parenthesis to cancel!
  3. Before the right parenthesis, it is not the corresponding left parenthesis, then the string must not be a valid parenthesis!
bool isValid(string s) {
    if (s.size() % 2) {
        return false;
    }
    unordered_map<char, char> pairs = {
        {')', '('},
        {']', '['},
        {'}', '{'}
    };
    stack<char> stk;
    for (char ch : s) {
        if (pairs.count(ch)) {
            if (stk.empty() || stk.top() != pairs[ch]) {
                return false;
            }
            stk.pop();
        } else {
            stk.push(ch);
        }
    }
    return stk.empty();
}

Method 2: Stack

bool isValid(string s) {
    if (s.size() % 2) {
        return false;
    }
    stack<char> st;
    for (auto ss : s) {
        if (ss == '(') {
            st.push(')');
        } else if (ss == '[') {
            st.push(']');
        } else if (ss == '{') {
            st.push('}');
        } else {
            if (st.empty() || st.top() != ss) {
                return false;
            } else {
                st.pop();
            }
        }
    }
    return st.empty();
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记