nikunjsoni

159

Jun 15th, 2021
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int lengthOfLongestSubstringTwoDistinct(string s) {
  4.         unordered_map<char, int> cnt;
  5.         int n=s.length(), left=0, right=0, ans=0;
  6.         for(right=0; right<n; right++){
  7.             cnt[s[right]]++;
  8.             while(left<right && cnt.size()>2){
  9.                 if(--cnt[s[left]] == 0) cnt.erase(s[left]);
  10.                 left++;
  11.             }
  12.             ans = max(ans, right-left+1);
  13.         }
  14.         return ans;
  15.     }
  16. };
Advertisement
Add Comment
Please, Sign In to add comment