Can anyone help to find what's the problem with my solution plz?


  • 0
    L

    It's a solution from my data structure book actually.
    when I submit it shows that I get wrong answer when the test case is "){". However, It could work well in my compiler(Dev-c++) and it's still ok when I run it on LeetCode when I input that test case by myself.
    Like this:
    1_1501727395670_微信图片_20170803102923.png 0_1501727395668_微信图片_20170803102857.png

    So here's my solution.

    
    class Solution {
    public:
        bool isValid(string s) {
     	stack<char>ans;
        getline(cin,s);
        bool isMatched=true;
        int i=0;
        char x;
       while(isMatched&&i<s.size())
       {
       	if(s[i]=='('||s[i]=='['||s[i]=='{') 
    	   ans.push(s[i]);
       	if(s[i]==')'||s[i]==']'||s[i]=='}')
       	{
       		if(ans.empty())
       		return false;
       		else{
       			x=ans.top();
       			if(((x=='(')&&(s[i]==')'))||((x=='[')&&(s[i]==']'))||((x=='{')&&(s[i]=='}')))
       			    isMatched=true;
       			else return false;
       			ans.pop();
    		   }
    	   }	
    	i++;
    	}
    	if(!ans.empty())
    	return false;
    	
    	return true;
        }
    };
    

    Thank you in advance<3


  • 0
    L

    Ohhhhh I know where's the problem.
    I mistakenly wrote this line.

    getline(cin,s);
    

    Anyway, problem solved. Ha.


Log in to reply
 

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