码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_20_Valid Parentheses

时间:2015-02-10 11:23:26      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   stack   

麻烦各位朋友帮忙顶一下增加人气,如有错误或疑问请留言纠正,谢谢技术分享


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.

关于堆栈的知识回顾:
#include <stack>
empty() 堆栈为空则返回真
pop() 移除栈顶元素
push() 在栈顶增加元素
size() 返回栈中元素数目
top() 返回栈顶元素
stack<int> a   定义一个堆栈


//vs2012测试代码
#include<iostream>
#include<string>
#include<stack>

using namespace std;

class Solution {
public:
    bool isValid(string s) 
	{
		stack<char> temp;
		for(int i=0; i<s.length(); i++)
		{
			if( !temp.empty() )
			{
				if( temp.top()=='(' && s[i]==')'
					|| temp.top()=='[' && s[i]==']'
					|| temp.top()=='{' && s[i]=='}')
						temp.pop();
				else
					temp.push(s[i]);
			}
			else
				temp.push(s[i]);
		}
		return temp.empty();
    }
};

int main()
{
	string s;
	getline( cin , s);  //或者cin>>s;
	Solution lin;
	cout<<lin.isValid(s)<<endl;

	return 0;
}

//方法一:自测Accepted
class Solution {
public:
    bool isValid(string s) 
	{
		stack<char> temp;
		for(int i=0; i<s.length(); i++)
		{
			if( !temp.empty() )
			{
				if( temp.top()=='(' && s[i]==')'
					|| temp.top()=='[' && s[i]==']'
					|| temp.top()=='{' && s[i]=='}')
						temp.pop();
				else
					temp.push(s[i]);
			}
			else
				temp.push(s[i]);
		}
		return temp.empty();
    }
};

//方法二:其他人版本
class Solution {
public:
    bool matchBracket(char a, char b)
    {
        if(a == '[' && b == ']') return true;
        if(a == '(' && b == ')') return true;
        if(a == '{' && b == '}') return true;
        return false;
    }
    bool isValid(string s) {
        stack<char> charStack;
        for(int i = 0; i < s.size(); ++i)
        {
            if(charStack.empty() || !matchBracket(charStack.top(), s[i])) charStack.push(s[i]);
            else charStack.pop();
        }
        
        return charStack.empty();
    }
};


leetcode_20_Valid Parentheses

标签:c++   leetcode   stack   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43699543

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!