C++ O(n)
cpp\nint longestBeautifulSubstring(string w) {\n    int res = 0;\n    for (int i = 0, j = 0; i < w.size(); ++i) {\n        if (w[i] == \'a\') {\n            int
```cpp\nint longestBeautifulSubstring(string w) {\n    int res = 0;\n    for (int i = 0, j = 0; i < w.size(); ++i) {\n        if (w[i] == \'a\') {\n            int cnt = 0;\n            for (j = i + 1; j < w.size() && w[j - 1] <= w[j]; ++j)\n                cnt += w[j - 1] < w[j];\n            if (cnt == 4)\n                res = max(res, j - i);\n            i = j - 1;\n        }\n    }\n    return res;\n}\n```
[]