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

leetcode_20题——Valid Parentheses(string,stack堆栈)

时间:2015-04-20 12:59:20      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:

Valid Parentheses

 Total Accepted: 47887 Total Submissions: 180550My Submissions

 

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.

 

Hide Tags
 Stack String
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

#include<iostream>
#include<string>
#include <stack>
using namespace std;

char change_char(char a)
{
	switch(a)
	{
	case ‘(‘:{return ‘)‘;break;}
	case ‘)‘:{return ‘(‘;break;}
	case ‘{‘:{return ‘}‘;break;}
	case ‘}‘:{return ‘{‘;break;}
	case ‘[‘:{return ‘]‘;break;}
	case ‘]‘:{return ‘[‘;break;}
	}
}
/*采用堆栈的方法,在是前括号时将其压入到堆栈中,是反括号时进行匹配
*/
bool isValid(string s) {
	stack<char> str_temp;
	if(s[0]==‘(‘||s[0]==‘[‘||s[0]==‘{‘)
		str_temp.push(s[0]);
	else
		return 0;

	int i=1;
	int len=s.size();
	while(i<len)
	{
		if(s[i]==‘(‘||s[i]==‘[‘||s[i]==‘{‘)//是前括号
		{str_temp.push(s[i]);i++;}
		else//是反括号
		{
			if(str_temp.empty())//栈里为空
				return 0;
			else
			{
				if(str_temp.top()!=change_char(s[i]))//不匹配
					return 0;
				str_temp.pop();
				i++;
			}
		}
	}
	if(str_temp.empty())//栈中是否为空
		return 1;
	else
		return 0;	
}
int main()
{
	string s="()";
	cout<<isValid(s)<<endl;
	system("pause");
	return 1;
}

  

leetcode_20题——Valid Parentheses(string,stack堆栈)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4440979.html

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