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;
}