分而治之O(nlogn)
可以优化到O(n)
每次找到分界点(大小写不全在的点)
小tip 大小写转换 ‘A’ ^ 32 = ‘ ‘, ‘a’ ^ 32 = ‘A’
class Solution {
public:
string longestNiceSubstring(string s) {
if (s.size() == 2) return s[0] == (s[1] ^ ' ') ? s : "";
unordered_set<char> mp(s.begin(), s.end());
string ans;
vector<int> split;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (!(mp.count(c) && mp.count(c ^ ' ')))
split.push_back(i);
}
if (split.empty()) return s;
split.insert(split.begin(), -1);
split.push_back(s.size());
for (int i = 0; i < split.size() - 1; i++) {
int l = split[i] + 1, r = split[i + 1] - 1;
if (r - l + 1 <= 1) continue;
auto res = longestNiceSubstring(s.substr(l, r - l + 1));
if (res.size() > ans.size()) ans = res;
}
return ans;
}
};