题解 | 穷哈哈~

穷哈哈~

https://www.nowcoder.com/practice/5b3184b233f34fb39a7f259ae82eb42c

用了一个比较麻烦的方法:使用栈来进行模拟。栈的size代表当前维护的合法子串长度,遇到a, h只要它和栈顶组成"ah" "ha"即入栈,如果不符合代表当前子串已达最大合法长度,全部出栈。

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    int len, idx = 0;
    cin >> len;
    cin >> s;
    stack<int> stk;
    int res = 0;
    while (idx < len) {
        if (s[idx] != 'a' && s[idx] != 'h') {
            res = max(res, (int)stk.size());
            while (!stk.empty()) stk.pop();
        } else {
            if (stk.empty()) {
                stk.push(s[idx]);
            } else {
                if (s[idx] == 'a') {
                    if (stk.top() == 'h') {
                        stk.push(s[idx]);
                    } else {
                        res = max(res, (int)stk.size());
                        while (!stk.empty()) stk.pop();
                        stk.push(s[idx]);
                    }
                }
                else if (s[idx] == 'h') {
                    if (stk.top() == 'a') {
                        stk.push(s[idx]);
                    } else {
                        res = max(res, (int)stk.size());
                        while (!stk.empty()) stk.pop();
                        stk.push(s[idx]);
                    }
                }
            }
        }
        idx++;


    }
    res = max(res, (int)stk.size());
    cout << res;

}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务