Longest Substring with At Most Two Distinct Characters
2016-05-07 20:37
330 查看
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.
For example, Given s = “eceba”,
T is “ece” which its length is 3.
namespace ConsoleApplication3 { using System; using System.Collections.Generic; class Program { private static string maxSubStrWithNChars(string str, int n) { if (n < 1) return ""; int s = 0, e = 0, maxS = 0, maxLen = 0; Dictionary<char, int> dic = new Dictionary<char, int>(); while (s <= e && e < str.Length) { while (e < str.Length && dic.Count <= n) { if (!dic.ContainsKey(str[e])) { dic.Add(str[e], 1); } else { ++dic[str[e]]; } if (e - s + 1 > maxLen && dic.Count <= n) { maxLen = e - s + 1; maxS = s; } ++e; } while (s <= e && dic.Count > n) { if (--dic[str[s]] == 0) { dic.Remove(str[s]); } ++s; } } return str.Substring(maxS, maxLen); } static void Main(string[] args) { string str1 = ""; //expect: 0 "" string str2 = "a"; //expect: 1 "a" string str3 = "aa"; //expect: 2 "aa" string str4 = "aba"; //expect: 3 "aba" string str5 = "abcd"; //expect: 2 "ab" string str6 = "abcdedcba"; //expect: 3 "ded" string str7 = "abbcdededcba"; //expect: 5 "deded" string str8 = "eceba"; //expect: 3 "ece" string str9 = "abaece"; //expect: 3 "aba" string str10 = "ababcd"; //expect: 4 "abab" string str11 = "cababcd"; //expect: 4 "abab" string str12 = "abcdefgabcdefg";//expect: 2 "ab" string str13 = "ababababababab";//expect: 14 "ababababababab" Console.WriteLine(maxSubStrWithNChars(str1, 2)); Console.WriteLine(maxSubStrWithNChars(str2, 2)); Console.WriteLine(maxSubStrWithNChars(str3, 2)); Console.WriteLine(maxSubStrWithNChars(str4, 2)); Console.WriteLine(maxSubStrWithNChars(str5, 2)); Console.WriteLine(maxSubStrWithNChars(str6, 2)); Console.WriteLine(maxSubStrWithNChars(str7, 2)); Console.WriteLine(maxSubStrWithNChars(str8, 2)); Console.WriteLine(maxSubStrWithNChars(str9, 2)); Console.WriteLine(maxSubStrWithNChars(str10, 2)); Console.WriteLine(maxSubStrWithNChars(str11, 2)); Console.WriteLine(maxSubStrWithNChars(str12, 2)); Console.WriteLine(maxSubStrWithNChars(str13, 2)); } } }
相关文章推荐
- c#调用COM组件
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#实现给图片加水印的方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#中的delegate委托类型基本学习教程
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- 举例讲解C#中自动实现的属性
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#比较二个数组并找出相同或不同元素的方法