首页 > 其他 > 详细

Leetcode 159: Longest Substring with At Most Two Distinct Characters

时间:2017-12-18 10:43:13      阅读:240      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/liangmou/p/8055988.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!