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

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)