原题目没找到,回忆大致如下:
输入(),输出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;
}
随便测了几个用例: