面试算法(每更两题):链表、队列、栈(四)

7.检查括号是否匹配

bool IsLeftParenthese(char c){
	return (c == '(') ||
		(c == '[') || (c == '{');
}

bool IsMatch(char left, char c){
	if (left == '(')
		return c == ')';
	if (left == '[')
		return c == ']';
	if (left == '{')
		return c == '}';
	return false;
}

bool MatchParenthese(const char *p){
	stack<char> s;
	char cur;
	while (*p)
	{
		cur = *p;
		if (IsLeftParenthese(cur))
			s.push(cur);
		else{
			if (s.empty() || !IsMatch(s.top(), cur))
				return false;
			s.pop();
		}
		p++;
	}
	return s.empty();
}

int main(){
	char *p = "(({})[])[()]";
	bool bMatch = MatchParenthese(p);
	if (bMatch)
		cout << p << "括号匹配。\n";
	else
		cout << p << "括号不匹配。\n";
	return 0;
}

8.字符串仅包括小括号,寻找最长匹配的括号子串

int GetLongestParenthese(const char *p){
	int size = (int)strlen(p);
	stack<int> s;
	int answer = 0;
	int start = -1;
	for (int i = 0; i < size; i++){
		if (p[i] == '('){
			s.push(i);
		}
		else{
			if (s.empty())
				start = i;
			else{
				s.pop();
				if (s.empty())
					answer = max(answer, i - start);
				else
					answer = max(answer, i - s.top());

			}
		}
	}
	return answer;
}
    原文作者:二伟在努力
    原文地址: https://blog.csdn.net/weixin_39527549/article/details/84978256
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞