20. Valid Parentheses

Problem:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

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

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

思路

Solution (C++):

bool isValid(string s) {
    if (s.empty())      return true;
    stack<char> stk{};
    int len = s.length();
    for (int i = 0; i < s.length(); ++i) {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[')
            stk.push(s[i]);
        else if (s[i] == ')') {
            if (stk.empty() || stk.top() != '(')  return false;
            else  stk.pop();
        }
        else if (s[i] == '}') {
            if (stk.empty() || stk.top() != '{')  return false;
            else  stk.pop();
        }
        else if (s[i] == ']') {
            if (stk.empty() || stk.top() != '[')  return false;
            else  stk.pop();
        }
    }
    if (!stk.empty()) return false;
    return true;
}

性能

Runtime: 0 ms  Memory Usage: 6.2 MB

思路

Solution (C++):


性能

Runtime: ms  Memory Usage: MB

原文链接: https://www.cnblogs.com/dysjtu1995/p/12583868.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    20. Valid Parentheses

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/338179

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:28
下一篇 2023年3月1日 下午11:29

相关推荐