题目:检查一个字符串中的括号是否匹配
分析:
一般直觉想到的是利用栈来实现,当然还有一种办法是递归实现。代码较为简单,如下:
-
#include <iostream>
-
-
using namespace std;
-
-
void check_pair(char *p, int &count)
-
{
-
if ('\0' == *p)
-
return;
-
-
if ('(' == *p)
-
{
-
count++;
-
}
-
else if (')' == *p)
-
{
-
count--;
-
}
-
-
check_pair(p + 1, count);
-
-
}
-
-
int main()
-
{
-
int count = 0;
-
const int MAX_NUM = 3;
-
char *test_str[MAX_NUM] =
-
{
-
"fdsfdf(())" ,
-
")())ifsafg()" ,
-
"f)a)fh(xsdf)" ,
-
};
-
-
for (int i = 0; i < MAX_NUM; ++i)
-
{
-
check_pair(test_str[i], count);
-
cout << test_str[i] << " is: " << count << endl;
-
count = 0;
-
}
-
-
return 0;
-
}
阅读(692) | 评论(0) | 转发(0) |