栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【数据结构入门

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【数据结构入门

原题链接:Leetcode 20. Valid Parentheses

Given a string s 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.

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only ‘()[]{}’.

方法一:栈 思路:

栈的应用之括号匹配模板题

c++代码:
class Solution {
public:
    bool isValid(string s) {
        stack st;

        // 遍历整个字符串
        for(auto c : s){
            // 左括号就入栈
            if(c == '(' || c == '[' || c == '{'){
                st.push(c);
            }
            else{
                if(st.empty()){
                    return false;
                }
                if(st.top() == '(' && c == ')') st.pop();
                else if(st.top() == '[' && c == ']') st.pop();
                else if(st.top() == '{' && c == '}') st.pop();
                else
                    return false;
            }
        }

        if(!st.empty())
            return false;

        return true;
    }
};
复杂度分析:
  • 时间复杂度:O(n),字符串的长度
  • 空间复杂度:O(n)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000874.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号