面试现场写代码:括号匹配+实现栈

原题目没找到,回忆大致如下:

输入(),输出0;

输入(((,输出3;

输入)))()(,输出4;

......

(),这两个匹配上可以抵消,写出算法代码,需要自己实现栈。

代码如下:

#include <stdio.h>
#include <iostream>
using namespace std;
class Stack{
    typedef struct Node{
        int value;
        Node* next;
        public: Node(int value){
            this->value = value;
            this->next = NULL;
        }
    };
    private: Node* top = NULL;
    public: void push(int value){
        if(top == NULL){
            top = new Node(value);
        }else{
            Node* newNode = new Node(value);
            newNode->next= top;
            top = newNode;
        }
    }
    
    public: int pop(){
        if(top==NULL){
            cout<<"empty stack"<<endl;
            return -1;
        }else{
            int popvalue = top->value;
            top = top->next;
            return popvalue;
        }
    }
    
    public: int getTop(){
        if(top == NULL){
            return -1;
        }else{
            return top->value;
        }
    }
    
    bool isEmpty(){
        if(top ==NULL){
            return true;
        }else{
            return false;
        }
    }
};

int main(){
    string s;
    cin>>s;
    Stack stack;
    for(int i=0;i<s.length();i++){
        if(s[i]=='('){
            stack.push('(');
        }else{
            if(stack.getTop()=='('){
                stack.pop();
            }else{
                stack.push(')');
            }
        }
    }
    int count =0;
    while(!stack.isEmpty()){
        count++;
        stack.pop();
    }
    cout<<count<<endl;
}

随便测了几个用例:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值