Leetcode20.Valid_Parentheses

运用栈,若栈为空,则只要压入闭括号即为false。遇到开括号则压入;遇到闭括号则判断与栈顶的开括号是否匹配,若匹配则二者配对弹出,否则return false。结束后检查栈内是否仍有元素,若有则return false;反之,return true
时间复杂度:O(N)
C++代码:

class Solution {
public:
	bool isValid(string s) {
		stack<char> record;
		string::iterator it = s.begin();
		while (it != s.end())
		{
			if (record.empty())
			{
				if (*it == ')' || *it == ']' || *it == '}')
					return false;
				else
					record.push(*it);
			}
			else
			{
				if (*it == ')')
				{
					if (record.top() != '(')
						return false;
					else
						record.pop();
				}
				else if (*it == ']')
				{
					if (record.top() != '[')
						return false;
					else
						record.pop();
				}
				else if (*it == '}')
				{
					if (record.top() != '{')
						return false;
					else
						record.pop();
				}
				else
					record.push(*it);
			}
			it++;
		}
		if (record.empty())
			return true;
		return false;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82995640