题目:有个由’(’和’)’组成的字符串,求出其中最长的正确匹配子串,如((()()中是()()
分析:使用字符串进出栈来模拟括号的匹配,栈中保存没有进行匹配的字符串,扫描字符串,对于第i个字符,如果该字符为‘(’,则进栈,如果该字符为')',并且栈顶字符是‘(’,则进行匹配,否则不匹配,字符进栈。对于进行匹配的字符,判断以该右括号结尾的最大匹配子串(最大匹配子串即为该右括号向前到第一个未匹配字符之间的子串)比当前已找到的最长匹配子串长,此时更新最长匹配子串。
所以需要记录未匹配字符及未匹配字符在字符序列中的位置,所以堆栈元素类型:
struct Entry{ char ch; int position; Entry(char c, int p){ ch = c; position = p; //该字符在字符串中位置 } };
代码:
//一个由'('和')'组成的字符串序列,求出其中最长的正确匹配子串,如((()()中是()() char* MaxValidSequence(const char* seq){ int seqLen = strlen(seq); char* maxValidSeq = new char[seqLen+1]; int maxValidCount = 0; Entry** stack = new Entry*[seqLen]; int top = 0; for (int i=0; i<seqLen; i++){ if (top==0 || seq[i] == '(' || stack[top-1]->ch!='('){ //当前是左括号,或者右括号不匹配时,字符进栈 stack[top++] = new Entry(seq[i], i); } else {//右括号匹配时,匹配的左括号出栈 Entry* entry = stack[--top]; int matchCount = i-(top>0?stack[top-1]->position:-1); if (maxValidCount < matchCount){ memcpy(maxValidSeq, seq+i-matchCount+1, sizeof(char)*matchCount); maxValidCount = matchCount;; } delete entry; } } while (top>0){ delete stack[--top]; } delete[] stack; maxValidSeq[maxValidCount] = '\0'; return maxValidSeq; }
正确匹配的最长的括号子串
最新推荐文章于 2022-01-05 21:15:34 发布