leetcode第十一周解题总结(155,150,20)--栈

知识点:Stack 栈


155. Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.


push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.


题意解析:
设计一个栈,包括push,pop,top操作,再加上一个取出最小值操作,该操作需要在常数时间内完成。


解题思路:
空间换时间,要在常数时间内取出最小值,考虑新增一个栈,存放当前最小值。入栈一个数的时候,计算当前最小值推入;出栈一个数,最小值的栈同样出栈一个值。

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> a;
    stack<int> min;
    MinStack() {
        while(!a.empty()) {
            a.pop();
            min.pop();
        }
    }

    void push(int x) {
        a.push(x);
        if(!min.empty()) {
            int temp = min.top()<x?min.top():x;
            min.push(temp);
        } else {
            min.push(x);
        }
    }

    void pop() {
        if (!a.empty()) {
            a.pop();
            min.pop();
        }
    }

    int top() {
        if (!a.empty()) {
            return a.top();
        } else {
            return NULL;
        }
    }

    int getMin() {

        if (!min.empty()) {
            return min.top();
        }else {
            return NULL;
        }
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

150. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
[“2”, “1”, “+”, “3”, “*”] -> ((2 + 1) * 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6

题意解析:
计算逆波兰表达式的值。


解题思路:
读入字符串后,将数字入栈,遇到加减乘除后,出栈两个数字进行运算后将结果入栈,如果没有两个数字代表不符合逆波兰表达式,这里不考虑这种情况。最后位于栈顶的就是所计算的值。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> cal;
        for(int i = 0; i < tokens.size(); i++){
            if(tokens[i]!="+" && tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/") {
                cal.push(atoi(tokens[i].c_str()));
            } else {
                int a = cal.top();
                cal.pop();
                int b = cal.top();
                cal.pop();
                int c = calculate(tokens[i],a,b);
                cal.push(c);
            }
        }
        return cal.top();
    }

    int calculate(string t, int a, int b) {
        int c;
        if(t == "+") {
            c = a + b;
        } else if (t=="-") {
            c = b - a;    
        } else if (t=="*") {
            c = a * b;  
        } else if (t=="/") {
            c = b/a;   
        }
        return c;
    }
};

20. Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
Subscribe to see which companies asked this question.

题意解析:
判对各种括号的使用是否合法,主要就是需要配对。


解题思路:
将字符串输入一个栈,如果与前一个匹配则出栈,否则入栈。如果最后栈内没有元素,则合法匹配。

class Solution {
public:
    bool isValid(string s) {
        stack<char> br;
        for (int i = 0; i < s.length(); i++) {
            if(!br.empty()) {
                if (isPair(br.top(),s.at(i)) ){
                    br.pop();
                    continue;
                }
            }
            br.push(s.at(i));

        }
        return br.empty();
    }

    bool isPair(char top, char s) {
        if (top == '(' && s == ')') {
            return true;
        }
        if (top == '{' && s == '}') {
            return true;
        }
        if (top == '[' && s == ']') {
            return true;
        }
        return false;
    }
};

总结:

C++使用stack对象的pop(),top()方法时需要注意当前栈是否为空,如果为空就会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值