[LeetCode] Longest Substring with At Most Two Distinct Characters
Problem Description
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”
,
T is "ece" which its length is 3.
This link has a nice solution to this problem using the sliding window technique. The code is rewritten as follows.
1 class Solution { 2 public: 3 int lengthOfLongestSubstringTwoDistinct(string s) { 4 int l = 0, r = -1, len = 0, n = s.length(); 5 for (int k = 1; k < n; k++) { 6 if (s[k] == s[k - 1]) continue; 7 if (r >= 0 && s[k] != s[r]) { 8 len = max(len, k - l); 9 l = r + 1; 10 } 11 r = k - 1; 12 } 13 return max(n - l, len); 14 } 15 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步