[算法] 括号匹配问题

问题

给定字符串,仅由”()[]{}”六个字符组成,设计算法,判断该字符串是否有效。其中括号以正确的顺序配对称之为有效,如:”()”、”()[]”都是有效的,但”([)]”是无效的。

分析

在考察第 i 位字符 c 与前面的括号是否匹配时:

  • 如果 c 为左括号,开辟缓冲区记录下来,希望 c 能够与后面出现的同类型最近右括号匹配
  • 如果 c 为右括号,则考察它能否与缓冲区中的左括号匹配,即检查缓冲区中最后出现的同类型左括号是否和 c 匹配

括号匹配的算法流程如下所示:

  1. 从前向后扫描字符串,若遇到左括号x,就压栈x;
  2. 若遇到右括号y,则:
    • 若发现栈顶元素x和该括号y匹配,则栈顶元素出栈,继续判断下一个字符;
    • 如果栈顶元素和该括号y不匹配,字符串不匹配;
    • 如果栈为空,则字符串不匹配;
  3. 扫描完成后,如果栈恰好为空,则字符串匹配,否则,字符串不匹配;

代码实现

算法具体实现如ParenthesesMatch.hpp所示

#ifndef ParenthesesMatch_hpp
#define ParenthesesMatch_hpp

#include <stdio.h>
#include <stack>

// 判断是否为左(小/中/大)括号
bool isLeftParentheses(char c) {
    return c == '(' || c == '[' || c == '{';
}

// 判断左括号和右括号是否匹配
bool isMatch(char left, char right) {
    if (left == '(') {
        return right == ')';
    }
    if (left == '[') {
        return right == ']';
    }
    if (left == '{') {
        return right == '}';
    }
    return false;
}

// 判断括号字符串是否匹配
bool isParenthesesMatch(char* p) {
    std::stack<char> s;
    char cur;
    while (*p) {
        cur = *p;
        if (isLeftParentheses(cur)) { // cur是左括号
            s.push(cur);
        } else {
            if (s.empty() || !isMatch(s.top(), cur)) { // cur是右括号并且当前栈顶为空或cur和栈顶括号不匹配,则不匹配
                return false;
            }
            s.pop();
        }
        p++;
    }
    return s.empty(); // 若最后栈不为空则不匹配
}

#endif /* ParenthesesMatch_hpp */

测试代码main.cpp如下

#include "ParenthesesMatch.hpp"

int main(int argc, const char * argv[]) {
    char* p = "(({})[])[()]";
    bool bMatch = isParenthesesMatch(p);
    if (bMatch) {
        printf("括号匹配....\n");
    } else {
        printf("括号不匹配...\n");
    }
    return 0;
}

扩展问题

给定字符串,只包含左括号”(“和右括号”)”,它可能不是括号匹配的,设计算法,找出最长匹配的括号子串,返回该子串的长度。如:

  • ((): 2
  • ()(): 4
  • ()(()): 6
  • (()()): 6

分析

  • 记起始匹配位置 s t a r t = 1 ,最大匹配长度为 m l ;考察第i位字符串 c
  • 如果 c 为左括号,压栈;
  • 如果 c 为右括号,则 c 可能与栈顶左括号匹配:
    • 如果栈为空,表示没有匹配的左括号, s t a r t = i ,为下一次可能的匹配左准备;
    • 如果栈不空,出栈(因为和 c 匹配了),出栈后:
      • 如果栈为空, i s t a r t 即为当前找到的匹配长度,检查 i s t a r t 是否比 m l 更大,使得 m l 得以更新;
      • 如果栈不为空,则当前栈顶元素t是上次匹配的最后位置,检查 i t 是否比 m l 更大,使得 m l 得以更新;
  • 注意:因为入栈的一定是左括号,先然没有必要将他们本身入栈,应该入栈的是该字符在字符串中的索引。

代码实现

// 计算最长匹配的括号子串
int getLongestParenthese(const char* p) {
    int size = (int)strlen(p);
    std::stack<int> s;
    int maxLength = 0; //记录最长匹配的括号子串的长度
    int start = -1;
    for (int i = 0; i < size; i++) {
        if (p[i] == '(') {
            s.push(i);  // 遇到左括号,压栈
        } else { // p[i] == ')'  // 遇到右括号
            if (s.empty()) { // 如果栈为空,start重新赋值
                start = i; //
            } else { // 栈不空,栈顶元素必为 '('
                s.pop();
                if (s.empty()) {
                    maxLength = std::max(maxLength, i-start);
                } else {
                    maxLength = std::max(maxLength, i-s.top());
                }
            }
        }
    }
    return maxLength;
}

猜你喜欢

转载自blog.csdn.net/zkp_java/article/details/80711050
今日推荐