[leetcode] 3. Longest Substring Without Repeating Characters
来源:互联网 发布:淘宝关键词重复有用吗 编辑:程序博客网 时间:2024/06/07 02:50
题目:
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.
题解:
使用i和j两个指针进行搜索,i代表候选的最长子串的开头,j代表候选的最长子串的结尾。
先假设i不动,那么在理想的情况下,我们希望可以一直右移j,直到j到达原字符串的结尾,此时j-i就构成了一个候选的最长子串。每次都维护一个max_length,就可以选出最长子串了。
实际情况是,不一定可以一直右移j,如果字符j已经重复出现过(假设在位置k),就需要停止右移了。记录当前的候选子串并和max_length做比较。接下来为下一次搜寻做准备。
在下一次搜寻中,i应该更新到k+1。这句话的意思是,用这个例子来理解,abcdef是个不重复的子串,abcdefc中(为了方便记录为abc1defc2),c1和c2重复了。那么下一次搜寻,应该跨过出现重复的地方进行,否则找出来的候选串依然有重复字符,且长度还不如上次的搜索。所以下一次搜索,直接从c1的下一个字符d开始进行,也就是说,下一次搜寻中,i应该更新到k+1。
public int lengthOfLongestSubstring(String s){int size=0;Set<Character> set=new HashSet<Character>();for(int i=0;i<s.length();i++){for(int right=i;right<s.length();right++){if(set.contains(s.charAt(right))){size=Math.max(size, set.size());set.clear();break;}elseset.add(s.charAt(right));}}return Math.max(size, set.size());}
- [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
- Spring AOP中pointcut expression表达式解析
- unity 关于计算时间的差值 时间戳
- Unity2D射线检测以及collider的事件发送
- 文件和目录操作命令 ls cd cp
- Construct Binary Tree from Preorder and Inorder Traversal问题及解法
- [leetcode] 3. Longest Substring Without Repeating Characters
- POJ1298算法解析
- xpath爬取首页信息,并获取详情页标题与时间
- poj 2945 Find the Clones
- robotframework源码解析
- oracle中的decode函数
- 结构体元素做函数参数和结构指针做函数参数
- 学习方法总结——《快速学习》总结
- RESTEASY003130: Class is not a root resource的问题原因