[LeetCode]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.

思考:{ [ ( 入栈,) ] } 出栈匹配。

class Solution {

public:

    bool isValid(string s) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

        int len=s.size();

		int i;

		bool ans=true;

		stack<char> p;

		char temp;

		for(i=0;i<len;i++)

		{

			if(s[i]=='('||s[i]=='['||s[i]=='{')

				p.push(s[i]);

			else if(s[i]==')')

			{

				if(p.empty()) return false;

				else

				{

					temp=p.top();

					if(temp!='(') return false;

					p.pop();

				}

			}

			else if(s[i]==']')

			{

				if(p.empty()) return false;

				else

				{

					temp=p.top();

					if(temp!='[') return false;

					p.pop();

				}

			}

			else if(s[i]=='}')

			{

				if(p.empty()) return false;

				else

				{

					temp=p.top();

					if(temp!='{') return false;

					p.pop();

				}

			}

		}

		if(p.size()>0) return false;

		return ans;

    }

};

2014-03-27 16:13:30

class Solution {

public:

    bool isValid(string s) {

        int len=s.size();

        if(len==0) return true;

        stack<char> temp;

        int i=0;

        char ch;

        while(i<len)

        {

            if(s[i]=='('||s[i]=='['||s[i]=='{') temp.push(s[i]);

            else

            {

                if(temp.empty()) return false;

                ch=temp.top();

                if(s[i]==')'&&ch!='(') return false;

                if(s[i]==']'&&ch!='[') return false;

                if(s[i]=='}'&&ch!='{') return false;

                temp.pop();

            }

            i++;

        }

        if(!temp.empty()) return false;

        else return true;

    }

};

  

你可能感兴趣的:(LeetCode)