# [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 };

|
9月前
Leetcode 516. Longest Palindromic Subsequence

32 0
|
11月前
|

LeetCode刷题---Two Sum（一）
LeetCode刷题---Two Sum（一）
|
9月前
|

Leetcode 11. Container With Most Water

36 3
|
9月前
|
Java
Leetcode 3. Longest Substring Without Repeating Characters

36 3
|
9月前
Leetcode 4. Median of Two Sorted Arrays

21 0
|
11月前
|

|

LeetCode - #2 Add Two Numbers

64 0
|

LeetCode - #1 Two Sum

48 0
|
2天前
|

【Leetcode刷题Python】从列表list中创建一颗二叉树

12 7
|
2天前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III

13 6