classSolution: defnumberOfSubstrings(self, s: str) -> int: need = 3 ans = left = 0 cnt = [0] * 3 for right, ch inenumerate(s): c = ord(ch) - ord("a") # 1. 入窗口 cnt[c] += 1 if cnt[c] == 1: need -= 1 # 2. 出窗口,維持窗口在向左延伸即可滿足條件的狀態 while need == 0: c = ord(s[left]) - ord("a") cnt[c] -= 1 if cnt[c] == 0: need += 1 left += 1 # 3. 累加答案,此時 [0, left - 1] 都是合法的左端點 ans += left return ans
classSolution { public: intnumberOfSubstrings(string s){ int n = s.size(); int ans = 0, left = 0, need = 3; vector<int> cnt(3); for (char& ch : s) { // 1. 入窗口 if (++cnt[ch - 'a'] == 1) need--; // 2. 出窗口,維持窗口在向左延伸即可滿足條件的狀態 while (need == 0) { if (--cnt[s[left] - 'a'] == 0) need++; left++; } // 3. 累加答案,此時 [0, left - 1] 都是合法的左端點 ans += left; } return ans; } };
方法二:維護每個字母最後出現的位置
1 2 3 4 5 6 7 8 9
classSolution: defnumberOfSubstrings(self, s: str) -> int: ans = 0 last = [-1] * 3 for i, ch inenumerate(s): last[ord(ch) - ord("a")] = i # 此時 [0, min(last)] 都是合法的左端點 ans += min(last) + 1 return ans