Where is the error?need help


  • 0
    J

    this is answer,and I need some further describtions.like "(())", in this situation,the answer is 2?

    #include "iostream"
    #include "cstdio"
    #include "cstring"

    using namespace std;
    
    struct Node {
    	char val;
    	struct Node *next;//定义一个指向Node的next结点
    };
    
    void push(struct Node** top_pt,char new_data){
    	struct Node *top=(struct Node *)malloc(sizeof(struct Node	));
    	top->val=new_data;
    	top->next=*top_pt;
    
    	*top_pt=top;
    }
    
    void pop(struct Node** top_pt){
    	//出栈
    	struct Node*top=*top_pt;
    	if (top==NULL){
    		printf("out of memory\n");
    		exit(0);
    	}
    	else{
    		int res=top->val;
    		*top_pt=top->next;
    		free(top);
    	}
    }
    
    int longestValidParentheses(char tokens[]){
    	struct Node *top=(struct Node*)malloc(sizeof(tokens));
    	top->next=NULL;
    	int length=strlen(tokens);
    	int i,count=0;
    	for ( i=0;i<length;i++){
    		if (tokens[i]=='('){
    			push(&top,'(');
    		}
    		else if (tokens[i]==')'){
    			if (top->val==NULL){
    				count=0;
    			}
    			else{
    				count++;
    				pop(&top);
    			}
    		}
    	}
    
    	return count;
    }
    
    
    int main(){
    	char tokens[]=")()())";
    	cout<<evalRPN(tokens)<<endl;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.