Leetcode 3. Longest Substring Without Repeating Characters
来源:互联网 发布:servo guide软件下载 编辑:程序博客网 时间:2024/06/04 22:01
题意:求字符串中的最长非重复子串
思路 :用O(n)即可
要求知道每次字符的上一次出现的位置
例如
0 1 2 3 4 5
a a b c b c
首先将每个字符的上次位置初始化为-1,左边界left设为0,当前子串长度now_sum为0
遍历过程:
i=0: a的上次位置为-1,小于边界0,故now_sum加1。同时a的上次位置变成0
i=1: a的上次位置为0,大于等于边界0,所以再利用原边界将出现重复。故先计算now_sum与ans的大小,接着再重置now_sum为当前位置减上次位置。最后再把左边界设为上次位置+1,即为1
i=2 : now_sum++
i=3: now_sum++
i=4:发现b的上次位置为2,大于边界1,故ans变成3,同时左边界变成3.
……同理
class Solution {public: int lengthOfLongestSubstring(string s) { int last_char[250],left,ans,i,n,c,now_sum; for(i=0;i<250;i++) last_char[i]=-1; left=0; ans=0; now_sum=0; n=s.length(); for(i=0;i<n;i++) { c=s[i];//字符ASCII码 if(last_char[c]>=left) //若上一个同字符位置大于等于左边界,则修改边界 { if(now_sum>ans) ans=now_sum; now_sum=i-last_char[c]; //新的now_sum值为当前位置减去上一个字符位置 left=last_char[c]+1; //边界为上一个字符位置+1 } else { now_sum++; } last_char[c]=i; //此字符的上一个位置 } if(now_sum>ans) ans=now_sum; return ans; }};
0 0
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- [leetcode] 3. Longest Substring Without Repeating Characters
- [Leetcode]3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- 【Leetcode】3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode - 3.Longest Substring Without Repeating Characters
- Leetcode 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters LeetCode
- (Leetcode)3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3. Longest Substring Without Repeating Characters
- Android中的BroadCastReceiver(广播接收者)
- UE4的AI学习(2)——官方案例实例分析
- TO:程序员,怎样维护好你的人际关系?
- c++怎样去启动电脑的其他程序
- 欢迎使用CSDN-markdown编辑器
- Leetcode 3. Longest Substring Without Repeating Characters
- 关于Maven+SpringMvc4.2版本返回json配置
- hdu 2819 Swap(二分匹配+记录路径,好题)
- 【mysql的设计与优化专题(4)】表的垂直拆分和水平拆分
- 黑马程序员:3分钟带你读懂C/C++学习路线
- Rxjava源码(三)-----线程控制Scheduler
- [HDU 5475] An easy problem (线段树)
- oracle数据导出提示EAP-00091解决办法
- slave_exec_mode对slave影响