leecode 解题总结:20. Valid Parentheses

#include 
#include 
#include 
#include 

using namespace std;
/*
问题:
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.

Subscribe to see which companies asked this question

分析:
Parentheses:圆括号
就是判断圆括号是否一一匹配,这个题目是剑指offer上的。
可以用栈来做:每次遇到左边的括号,都压入到栈中,每次遇到右边的栈就弹出,判断是否匹配,即可。
如果出现栈中括号不匹配,就说明不符合
时间复杂度为O(n)

输入:
]
()[]{}
([)]
([{}])
输出:
no
yes
no
yes

关键:
1 			case ')':
			case ']':
			case '}':
				//易错,取元素之前需要判空
				if(brackets.empty())
				{
					return false;
				}
*/

class Solution {
public:
	//判断括号是否匹配
	bool isMatch(char ch , char bracket)
	{
		if( ')' == ch)
		{
			if('(' == bracket)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if(']' == ch)
		{
			if('[' == bracket)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else if('}' == ch)
		{
			if('{' == bracket)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}

    bool isValid(string s) {
        if(s.empty())
		{
			return false;
		}
		int len = s.length();
		stack brackets;
		char ch;
		char bracket;
		for(int i = 0 ; i < len ; i++)
		{
			ch = s.at(i);
			switch(ch)
			{
			case '(':
				brackets.push(ch);
				break;
			case '[':
				brackets.push(ch);
				break;
			case '{':
				brackets.push(ch);
				break;
				//取出栈中的括号,看是否匹配
			case ')':
			case ']':
			case '}':
				//易错,取元素之前需要判空
				if(brackets.empty())
				{
					return false;
				}
				bracket = brackets.top();
				//如果不匹配,直接输出false
				if(!isMatch(ch , bracket))
				{
					return false;
				}
				else
				{
					brackets.pop();
				}
				break;
			default:
				return false;
			}
		}
		//判断如果此时栈不空,说明不匹配
		if(brackets.empty())
		{
			return true;
		}
		else
		{
			return false;
		}
    }
};

void process()
{
	string bracket;
	Solution solution;
	while(cin >> bracket)
	{
		bool isOk = solution.isValid(bracket);
		if(isOk)
		{
			cout << "yes" << endl;
		}
		else
		{
			cout << "no" << endl;
		}
	}
}

int main(int argc , char* argv[])
{
	process();
	getchar();
	return 0;
}

你可能感兴趣的:(leecode)