网上有些例子有问题,所以重新写了下 求字符串的最长不重复字串
2016-05-10 10:14
169 查看
假设有一个字符串“abcdebfgh”
那么最长不重复字串是"cdebfgh",长度是7
若是:abcdbefbghijij
应输出:befbghij
那么最长不重复字串是"cdebfgh",长度是7
若是:abcdbefbghijij
应输出:befbghij
以abcbef这个串为例 用一个数据结构pos记录每个元素曾出现的下标,初始为-1 从s[0]开始,pos['a'] == -1,说明a还未出现过,令pos['a'] = 0,视为将a"加入当前串",同时长度++ 同理令pos['b'] = 1,pos['c'] = 2 到s[3]时,pos['b'] != -1,说明'b'在前面已经出现过了,此时可得到一个不重复串"abc",刷新当前的最大长度,然后做如下处理: pos[s[0~2]] = -1,亦即将"ab""移出当前串",同时当前长度减去3 重复以上过程 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication10 { class Program { static void Main(string[] args) { string ss = "abcdbefbghijij"; var list = ss.ToCharArray(); int left = 0; int right = 0; GetLen(list, out left, out right); Console.WriteLine(ss.Substring(left, right - left + 1)); } /// <summary> /// /// </summary> /// <param name="list"></param> /// <param name="left">right index from 0</param> /// <param name="right">right index from 0</param> /// <returns></returns> public static int GetLen(char[] list, out int left, out int right) { if (list == null || list.Length <= 0) { throw new Exception("the input list length is 0"); } int len = list.Length; left = 0; right = 0; int maxLen = 0; int start = 0; int tempMaxLen = 0; Dictionary<char, int> cache = new Dictionary<char, int>(); for (int i = 0; i < len; i++) { if (!cache.Keys.Contains(list[i]) || cache[list[i]]==-1) //这个建不存在或者有建,但是值为-1,表明这个字符还没出现过. { tempMaxLen++; cache.Add(list[i], i); } else { //there is duplicated char abcdbefgh if (tempMaxLen > maxLen) { maxLen = tempMaxLen; left = start; right = i - 1; } tempMaxLen = i - cache[list[i]]; for (int j = start; j < cache[list[i]]; j++) // 注意:网上好多例子是清楚这个cache里所有的,应该是错误的;仅仅应该清楚上次重复字符前面的字符。 { cache[list[j]] = -1; } start = cache[list[i]] + 1; cache[list[i]] = i; } } if (tempMaxLen > maxLen) { maxLen = tempMaxLen; left = start; right = len-1; } return maxLen; } } }
相关文章推荐
- 对象的访问定位
- 阿里、百度、搜狐等公司社招面试记录与总结(转)
- iOS开发笔记--Charles网络封包分析工具的使用
- lucene .NET 搜索图片 功能实现
- 用jekyll制作高大上的网站(一)——安装与配置
- java 匿名内部类
- Linux下安装node.js5.10.1
- 百度图片爬虫-python版-如何爬取百度图片?
- JS获取终端屏幕、浏览窗口的相关信息
- 数组-Find Minimum in Rotated Sorted Array
- 转 STL之vector的使用
- solrCloud+tomcat+zookeeper集群配置
- org.springframework.beans.factory.BeanCreationException: Error creating bean with name 这个错误完美解决
- 8.1 MySQL 应用基础
- 1 栈-OOP
- qq分享报 : EQQAPIAPPSHAREASYNC
- iframe跨域传输数据(二)---- MessengerJS ; 实现子页面父页面数据传输;
- 技术总结
- POJ 3278 The merchant
- java增强for循环总结