您的位置:首页 > 其它

如何判断一个字符串中的括号是否匹配

2015-09-23 00:30 302 查看
描述:给定一个包含"(",")","[","]"的字符串,如果判断这个字符串中的括号是否正确匹配,匹配输出YES,否则输出NO;

INPUT: [(S)a]

OUTPUT:YES

代码实现一:基于括号数量统计的方法

#include<iostream>

#include<string>

#include<cctype>

using namespace std;

bool match(char* str);

int main()

{

char str[100];

gets(str);

if (match(str))

{

cout << "YES" << endl;

}

else

cout << "NO" << endl;

return 0;

}

bool match(char* str)

{

int len = strlen(str);

int count_left_1 = 0, count_right_1 = 0;

int count_left_2 = 0, count_right_2 = 0;

char *p = str;

while (*p)

{

if (*p=='(')

{

++count_left_1;

}

if (*p==')')

{

++count_right_1;

}

if (*p == '[')

{

++count_left_2;

}

if (*p == ']')

{

++count_right_2;

}

if (count_right_1>count_left_1||count_right_2>count_left_2)

{

return false;

}

++p;

}

if (count_left_1 == count_right_1&&count_left_2 == count_right_2)

{

return true;

}

else

return false;

}

代码实现二:基于栈的思想

#include<iostream>

#include<cstring>

#include <vector>

#include <string>

using namespace std;

int main()

{

char str[100] = { '0' };

while (cin >> str)

{

bool isBracket = false;

int len = strlen(str);

vector<char> stack;

for (int i = 0; i < len; ++i)

{

int size;

size = stack.size();

if (str[i] == '(')

{

if (size>0 && stack.at(size - 1) == ')')

{

stack.pop_back();

}

else

stack.push_back(str[i]);

isBracket = true;

}

else if (str[i] == ')')

{

isBracket = true;

if (size > 0 && stack.at(size - 1) == '(')

{

stack.pop_back();

}

else

stack.push_back(str[i]);

}

else if (str[i] == '[')

{

isBracket = true;

if (size > 0 && stack.at(size - 1) == ']')

{

stack.pop_back();

}

else

stack.push_back(str[i]);

}

else if (str[i] == ']')

{

isBracket = true;

if (size > 0 && stack.at(size - 1) == '[')

{

stack.pop_back();

}

else

stack.push_back(str[i]);

}

}

if (stack.size() == 0&&isBracket)

{

cout << " YES " << endl;

}

else

{

cout << "NO" << endl;

}

}

return 0;

}

代码分析:

两种方法只需要遍历一次字符串,故时间复杂度为O(N);

方法一空间复杂度为O(N),方法二空间复杂度为O(1)

扩展:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: