首页 > 其他分享 >18933 括号匹配问题

18933 括号匹配问题

时间:2024-10-14 22:49:26浏览次数:3  
标签:匹配 string 18933 markers 括号 字符串 input stack

### 思路
1. **输入处理**:读取输入的字符串。
2. **匹配括号**:使用栈来匹配括号,记录无法匹配的左括号和右括号的位置。
3. **标注输出**:根据记录的位置,生成标注字符串,输出原始字符串和标注字符串。

### 伪代码
```
function process_string(input):
    stack = []
    markers = [' '] * len(input)

    for i from 0 to len(input) - 1:
        if input[i] == '(':
            stack.push(i)
        elif input[i] == ')':
            if stack is not empty:
                stack.pop()
            else:
                markers[i] = '?'

    while stack is not empty:
        markers[stack.pop()] = '$'

    return input, markers.join('')

function main():
    while input is not EOF:
        input = read_input()
        original, markers = process_string(input)
        print(original)
        print(markers)
```

### C++代码
 

#include <iostream>
#include <stack>
#include <cstring>
using namespace std;

void process_string(const string& input) {
    stack<int> s;
    string markers(input.length(), ' ');

    for (int i = 0; i < input.length(); ++i) {
        if (input[i] == '(') {
            s.push(i);
        } else if (input[i] == ')') {
            if (!s.empty()) {
                s.pop();
            } else {
                markers[i] = '?';
            }
        }
    }

    while (!s.empty()) {
        markers[s.top()] = '$';
        s.pop();
    }

    cout << input << endl;
    cout << markers << endl;
}

int main() {
    char s[205];
    while (scanf("%s", s) != EOF) {
        process_string(s);
    }
    return 0;
}

### 总结
1. **输入处理**:读取并存储输入字符串。
2. **匹配括号**:使用栈来匹配括号,记录无法匹配的括号位置。
3. **标注输出**:根据记录的位置,生成标注字符串,输出原始字符串和标注字符串。

标签:匹配,string,18933,markers,括号,字符串,input,stack
From: https://blog.csdn.net/huang1xiao1sheng/article/details/142930985

相关文章