II Hash Table: 2. Longest Substring Without Repeating Characters
2016-01-03 00:21
316 查看
3. Longest Substring Without Repeating Characters
given: a string, find the length of the longest substring without repeating characters.
e.g. 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.
one way to use HashSet to track the longest substring without repeating characters so far, use a fast pointer
j to see if character j is in the hash set or not, if not, great, add it to the has set, move j forward and update
the max length, otherwise, delete from the head by using a slow pointer i util we can put character j to the hash set
public class Solution{
public int lengthOfLongestSubstring(String s){
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j<s.length()){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
max=Math.max(max, set.size());
}else{
set.remove(s.charAt(i++));
}
}
return max;
}
}
given: a string, find the length of the longest substring without repeating characters.
e.g. 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.
one way to use HashSet to track the longest substring without repeating characters so far, use a fast pointer
j to see if character j is in the hash set or not, if not, great, add it to the has set, move j forward and update
the max length, otherwise, delete from the head by using a slow pointer i util we can put character j to the hash set
public class Solution{
public int lengthOfLongestSubstring(String s){
int i = 0, j = 0, max = 0;
Set<Character> set = new HashSet<>();
while (j<s.length()){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
max=Math.max(max, set.size());
}else{
set.remove(s.charAt(i++));
}
}
return max;
}
}
相关文章推荐
- 在Linux编写程序arm程序,通过usb烧写在Android系统中安装和运行C程序
- 【Error】Python:SyntaxError: Non-ASCII character '\xe5'解决方法
- 用归并排序处理逆序对问题
- 在window7下安装mysql
- class_create(),device_create自动创建设备文件结点
- RMI基础知识
- 比比Java和C#语言运行的快慢
- maven项目建立
- Logback与Log4J的区别
- grunt安装失败处理
- 1.ARC下是否有内存溢出等问题 2.@property参数 3.#import和@class的区别
- Android Tab实现之FragmentManager+Fragment
- 被误解的 MVC 和被神化的 MVVM
- 九度OJ 1361(反转) 1362(循环移位) 1363(判断) 1364(01背包) 1365(BFS)
- Shell编程进阶 2.2 shell数组
- Oracle事务隔离级别
- Shodan完全手册部分翻译(4)
- 2015年总结
- ?--Porg.springframework.beans.MethodInvocationException: Property 'username' threw exception; nested exception is java.lang.NullPointerException
- Android的context