每日一题3.11.2

每日一题3.11.2

题目描述:合法括号序的判断

**解题思路:**用一个left变量++ 和 - - 来监测左右括号,遇左括号++,遇右括号–,而且遇到右括号时left不能小于0.
代码实现:

#include<iostream>
#include<string>
using namespace std;
class Parenthesis {
public:
	bool chkParenthesis(string A, int n)
	{
		// write code here
		int left = 0;
		for (int i = 0; i < n; i++)
		{
			if (A[i] == '(')
				left++;
			else if (A[i] == ')')
			{
				if (left <= 0)
				{
					cout << "false";
					return false;
				}
				else
					left--;
			}
			else
			{
				if (left <= 0)
				{
					cout << "false";
					return false;

				}
			}
		}
		if (left == 0)
		{
			cout << "true";
			return true;
		}
		cout << "false";
		return false;
			

	}
};
int main()
{
		string A;
		cin >> A;
		Parenthesis p;
		size_t n = A.size();
		p.chkParenthesis(A, n);
		system("pause");
		return 0;
}

参考答案:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lxb18821659801/article/details/88527496