码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 159: Longest Substring with At Most Two Distinct Characters

时间:2017-12-18 12:40:29      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:turn   which   min   most   nta   leetcode   string   class   gpo   

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

标签:turn   which   min   most   nta   leetcode   string   class   gpo   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!