标签:
4 [] ([])[] ((] ([)]
0 0 3 2
先给出我的错误答案
基本思路就是利用栈的思想,从左到右遍历右括号,检查右括号的前一个括号是否匹配,匹配的话就成对删去,不匹配就添加括号。遍历一遍后,添加的个数再加上最后剩下未匹配的左括号数。
#include<iostream> using namespace std; int check(const char* str) { int ret = 0; std::string ope(str); auto iter = ope.begin(); for(;iter != ope.end();) { char i = *iter; if(i == ‘)‘) { if(iter == ope.begin()) { ret++; iter = ope.erase(iter); } else if(*(iter - 1) != ‘(‘) { ret++; iter = ope.erase(iter); } else { iter = ope.erase(iter-1); iter = ope.erase(iter); } } else if(i == ‘]‘) { if(iter == ope.begin()) { ret++; iter = ope.erase(iter); } else if(*(iter - 1) != ‘[‘) { ret++; iter = ope.erase(iter); } else { iter = ope.erase(iter-1); iter = ope.erase(iter); } } else iter++; } ret += ope.length(); return ret; } int main() { int len = check("([)]"); cout << len << endl; system("pause"); return 0; }
有明显的错误,比如 [(]]]]就错误了。。。待明天研究
标签:
原文地址:http://www.cnblogs.com/sdlwlxf/p/4328715.html