Longest Substring Without Repeating Characters
来源:互联网 发布:域名虚拟主机哪家好 编辑:程序博客网 时间:2024/06/04 18:31
1、题目
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
2、Time limit exceed 版本
举例来看:
abba->2
aab->2
abbb->2
abcad->4
考虑使用两个指针,N^2复杂度的解法:
int lengthOfLongestSubstring(string s) { if(s.empty()) return 0; if(s.size()==1) return 1; map<char,int> chMap; int i=0,len=s.size(); int ret=0,tmp=0,j=0; for(char ch=s[0];i<len;) { ch=s[i]; //没有找到,表示没有重复的,指针往前走 if(chMap.count(ch)==0) { chMap[ch]=1; tmp++; ++i; } else{ //碰到不同的,直接把map清除,i回到重复的那个元素位置 j=i; --i; while(s[i]!=s[j]) --i; chMap.clear(); if(ret<tmp) ret=tmp; ++i;//从重复元素下一个开始 ch=s[i]; chMap[ch]=1; tmp=1; ++i; } } //返回较大的值 if(ret<tmp) ret=tmp; return ret; }
结果,Time Limit Exceed !
3、时间复杂度更低:
贴了链接给出的答案:http://blog.csdn.net/feliciafay/article/details/16895637,竟然A了,分析下原因:
int lengthOfLongestSubstring(string s) { int n = s.length(); int i = 0, j = 0; //i是候选字符串的起点, j是候选字符串的终点。 int max_length = 0; int cur_length = 0; bool exist[256] = { false }; while (j < n) { if (!exist[s[j]]) { exist[s[j]] = true; //遍历过,记录为true j++; } else { while(s[i]!= s[j]) { exist[s[i]] = false; //新候选字串从第一个重复字符(当s[i] == s[j]时候的i)的后一位开始算,之前的i不算,等效于没有被扫描到,所以设为false. i++; } i++; j++; } cur_length = j - i; max_length = max_length > cur_length ? max_length : cur_length; } return max_length; }
分析原因:上面我的代码i会回退,而下段代码中,i为字符串起点,相同元素位置,记为k,k之前的字符相当于没有被扫描过。i回到k的下一个位置,j可以继续。很赞!
0 0
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- hdu 5288 OO’s Sequence(15多校第一场1001)
- uva11404(数论_三角形计数)
- 223 Rectangle Area
- ubuntu 查找文件方法,个人笔记
- 数据库的唯一标示符(ID)的选择
- Longest Substring Without Repeating Characters
- WPF 后台Render线程崩溃, Exception from HRESULT: 0x88980406
- linux scp 命令
- 字典
- UVa10391 string字符串处理
- 杭电ACM1570——A C~~水题
- 1151 - Buy or Build
- How many 0's?(求区间某一个数的个数,好题)
- svn代码版本管理总结