Leetcode 159: Longest Substring with At Most Two Distinct Characters

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 159: Longest Substring with At Most Two Distinct Characters相关的知识,希望对你有一定的参考价值。

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.

 

 1 public class Solution {
 2     public int LengthOfLongestSubstringTwoDistinct(string s) {
 3         if (s == null) return 0;
 4         if (s.Length < 2) return s.Length;
 5         
 6         var dict = new Dictionary<char, int>();
 7         
 8         int i = 0, j = 0, max = 0;
 9         
10         while (j < s.Length)
11         {
12             dict[s[j]] = j;
13             
14             if (dict.Count > 2)
15             {
16                 char toDelete = *;
17                 var min = Int32.MaxValue;
18                 
19                 foreach (var pair in dict)
20                 {
21                     if (pair.Value < min)
22                     {
23                         min = pair.Value;
24                         toDelete = pair.Key;
25                     }
26                 }
27                 
28                 i = min + 1;
29                 dict.Remove(toDelete);
30             }
31             else
32             {
33                 max = Math.Max(j - i + 1, max);
34             }
35             
36             j++;
37         }
38         
39         return max;
40     }
41 }

 

以上是关于Leetcode 159: Longest Substring with At Most Two Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 159. Longest Substring with At Most Two Distinct Characters 求两个字母组成的最大子串长度 --------- jav

[LeetCode] 340. Longest Substring with At Most K Distinct Characters

Leetcode: Longest Absolute File Path

Leetcode 14 Longest Common Prefix

159 Longest Substring with At Most Two Distinct Characters

leetcode-14 longest-common-prefix(最长公共前缀)