欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

算法与数据结构(栈)

程序员文章站 2022-06-03 13:33:27
...

STL中栈的基本操作

//定义或者声明一个栈
stack<int> int_stack; //也可以定义其他类型的stack<string> str_stack;
// 向栈中压入一个元素
int x;
int_stack.push(x);
//判断栈是否为空
int_stack.empty(); //若为空则返回1,否则返回0
//返回栈中元素的个数
int_stack.size();
//将栈顶元素弹出
int_stack.pop();
//获取栈顶元素
int y;
y = int_stack.top();

栈的应用(括号匹配)

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.
算法与数据结构(栈)

class Solution {
public:
    bool isValid(string s) {
        stack<char> str;
        
        for (int i=0; i<s.length(); i++)
        {
            if (s[i] == '(' || s[i] == '{' || s[i] == '[')
            {
                str.push(s[i]);
            }
            else if( str.empty() )
            {
                return false;
            }
            else
            {
                if( (str.top() == '(' && s[i] == ')') ||
                    (str.top() == '{' && s[i] == '}') ||                               
                    (str.top() == '[' && s[i] == ']')) 
                      str.pop();
                else
                {
                    return false;
                }
            }
        }
        return str.empty();
    }
};
  • 题目链接:https://leetcode.com/problems/valid-parentheses/

栈的实现(待更新。。。)

相关标签: 数据结构(栈)