b788中等

跳脫標記的內外字母

每次讀取一個語法單位,以深度分別登記內外字母。

解題思路

用索引i與非負深度depth掃描。未跳脫#若有下一字元,就把下一字元視為字面值並一口氣消耗兩字元;若是字母仍按目前depth登記,但任何括號或#都不執行功能。末尾孤立#直接略過。

其他字元中,[令深度加1,]令深度降至不小於0,字母則加入inside或outside集合。最後兩集合交集排序輸出,空交集輸出-。跳脫處理必須在括號判斷前完成,才能確保 #[ 不開啟新層;## 僅讓第二個#成為字面值。

時間 O(N+26 log26),空間 O(N+26),Python read/split 保存長度N字串;兩集合至多各26字母,N≤300。

Step-by-step animation

逐步推演(例子條件見步驟說明)

回報動畫錯誤
步驟 1 / 3

外部字母

自訂字串 a[a]#[,第一個a在深度0,加入外集合。

a
外部集合
a

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    int n;
    string s;
    cin >> n >> s;
    bool in[26] = {}, out[26] = {};
    int dep = 0;
    for (int i = 0; i < n;) {
        char c = s[i++];
        if (c == '#') {
            if (i == n)
                continue;
            c = s[i++];
            if (c >= 'a' && c <= 'z')
                (dep ? in : out)[c - 'a'] = true;
        } else if (c == '[')
            dep++;
        else if (c == ']')
            dep = max(0, dep - 1);
        else
            (dep ? in : out)[c - 'a'] = true;
    }
    string ans;
    for (int i = 0; i < 26; i++)
        if (in[i] && out[i])
            ans += char('a' + i);
    cout << (ans.empty() ? "-" : ans) << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多