LeetCode 3. Longest Substring Without Repeating Characters
来源:互联网 发布:交易软件 编辑:程序博客网 时间:2024/06/05 03:32
- 题目
- 题解
- 优化
【题目】
Given a string, find the length of the longest substring without repeating characters.Examples:Given "abcabcbb", the answer is "abc", which the length is 3.Given "bbbbb", the answer is "b", with the length of 1.Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
题解
这道题大意是找一个字符串中最长的没有重复字符的字符串。
我的解法比较普通,就是遍历字符串,利用string库的find函数,用一个sub记录没有重复字符的子字符串。代码如下:
int lengthOfLongestSubstring(string s){ string sub = "",max=""; for(int i = 0;i<s.size();i++){ if(sub.find(s[i]) != s.npos){ max = sub.size()>max.size()? sub : max; i = i-sub.size()+1; sub = ""; } sub+=s[i]; } max = sub.size()>max.size()? sub : max;}
优化
用自己的办法实现过后,在LeetCode的discussion上看到一个更快速的办法,跑leetCode测试用例,使用了22ms(上面的代码用了75ms)。其原理如下:
我们知道,被查找字符串使用的字符都是ASCII码,所以遍历这个字符串的时候,用一个大小为256的vector,记录字符串中每个字符在字符串中最后一次出现的的下标,比如dict['a']会被识别为dict[97]。
代码如下:
int lengthOfLongestSubstring(string s) { vector<int> dict(256, -1); int maxLen = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); } return maxLen;}
当然,如果我们可以假设,字符串是由a-zA-Z组成,这样,vector的长度可以够更少。
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
- Eclipse 注释模板设置
- 解决一个八阿哥bug的方法
- 深入理解javascript的定时机制
- win10下安装和配置nodejs
- 递归(一)几个简单的递归例子
- LeetCode 3. Longest Substring Without Repeating Characters
- Oracle常见死锁发生的原因以及解决方法
- Chapter 3 ADC and DAC
- Linux的3个文件时间
- 分布式定时任务解决方案-spring boot整合JMS以及Redis实现
- 点线面的融会贯通学习方法探讨
- 小白初装SQL Server 2008遇到的问题
- 跟小博老师一起学Servlet ——Servlet之HttpServletResponse
- 使用Notepad++批量转换源代码编码方式