LeetCode 3. Longest Substring Without Repeating Characters
来源:互联网 发布:php增删改查代码 编辑:程序博客网 时间:2024/06/05 16:59
3. Longest Substring Without Repeating Characters
一、问题描述
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.
三、解题思路
Set
- 判断是否出现重复,可以考虑使用set 集合来做。因为集合中的值是不允许重复的。首先遍历一遍string 添加到一个set中,set的大小,即时不重复子串的最大长度。
- 然后依次判断以 i 开头的不重复子串的长度是多少,并不断更新最大值,如果最大值达到了上面求出的最大子串的长度,那么就直接返回。在计算以 i 开头的子串长度时,遇到重复的直接返回,否则长度加一并继续遍历。
- 这个算法不是那么棒呦,复杂度应该是O(n2)
class Solution {public: int lengthOfLongestSubstring(string s) { if(s.size() == 0)return 0; if(s.size() == 1)return 1; int max = 0; set<char> tot; for (int i = 0, n = s.size(); i < n; ++i) { tot.insert(s[i]); } for (int i = 0, n = s.size(); i < n; ++i) { set<char> cache; cache.insert(s[i]); int count = 1; for (int j = i+1; j < n; ++j) { if(cache.find(s[j]) == cache.end()){ cache.insert(s[j]); count++; }else{ break; } } if(count > max)max = count; if(max == tot.size())break; } return max; }};
阅读全文
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
- 编写Linux内核模块实现阶乘
- 【CSDN常见问题解答】使用JNA调用Windows动态库
- Android Gradle Plugin解析
- c语言中怎么实现字符串转化数字的功能
- 前端性能优化补充
- LeetCode 3. Longest Substring Without Repeating Characters
- hive启动异常Cannot create directory /usr/hive-2.1.1/tmp/root/ff3fc24a-fa0e-4b85-a938-eac74b50df52. Name
- 822D My pretty girl Noora
- 设计模式的学习-(2)简单工厂模式
- HDU1698[JUST A HOOK] 线段树
- 前后端实现Base64格式的传参及转换
- web service简单了解
- 【总结】:本科毕业的简单总结
- OSI七层协议和tcp/ip四层协议详解