leetcode Longest Substring Without Repeating Characters
来源:互联网 发布:肯特州立大学知乎 编辑:程序博客网 时间:2024/05/22 13:49
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.
看到这道题目,因为是最优问题,首先第一反应是动态规划。当时使用动态规划,考虑每个字符的时候,都需要将前面组成的最长字符比较,时间复杂度必然不是最优的。
于是在网上搜了一下,发现一个比较不错的解法,利用的是string的组成是有范围的,而且是不重复元素,很快想到了hash。采用长度为256的元素对每个字符进行hash,用start记录当前子串的起始位置,如果当前字符的之前存在过,而且在start之后,那么就需要重新考虑这个substring了,start需要重新赋值了。
class Solution {public: int lengthOfLongestSubstring(string s) { int len=s.length(); if(len==0) return 0; vector<int> pos(256,-1); int longest=INT_MIN; int sublen=0; int start=0; for(int i=0;i<len;i++){ if(pos[s[i]]!=-1&&pos[s[i]]>=start){ sublen=i-pos[s[i]]; start=pos[s[i]]+1; } else{ sublen++; } pos[s[i]]=i; longest=sublen>longest?sublen:longest; } return longest; }};
0 0
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- UIbutton 常规使用
- c++音乐分类器essentia
- nand2tetris【7】
- Leetcode: Evaluate Reverse Polish Notation
- ==和equals方法
- leetcode Longest Substring Without Repeating Characters
- autoconfig和autoreconfig详解
- Ubuntu更新出现 The system is running in low-graphics mode解决方法
- Eclipse 设置保护色
- Spring IOC过程总结
- OCP-1Z0-051-题目解析-第20题
- 【Matlab】 meshgrid surf1
- nginx - 缓存过期影响因素的优先级分析
- 按钮点击事件的4种实现方法(2014.6.28)