Leetcode 3. Longest Substring Without Repeating Characters
来源:互联网 发布:java手机游戏免费下载 编辑:程序博客网 时间:2024/05/15 15:05
O(n)
public class Solution { public int lengthOfLongestSubstring(String s) { HashSet<Character> hs = new HashSet<Character>(); int max = 0, fast = 0, slow = 0; while (fast < s.length()) { if (!hs.add(s.charAt(fast))) { hs.remove(s.charAt(slow)); slow++; } else { // maintain the maximum length max = Math.max(max, fast-slow+1); fast++; } } return max; }}
O(n^2)
// using a hashset to save the sunstring starting from 0, 1, ..., n // keep recording the length for each substring// if max < current length, set max = current lengthpublic class Solution { public int lengthOfLongestSubstring(String s) { HashSet<Character> hs = new HashSet<Character>(); int max = 0; // check the length for substring starts from i for (int i=0; i<s.length(); i++) { // tmp to save the current substring's length int tmp = 0, j = i; while (j < s.length()) { // found a duplicate character if (!hs.add(s.charAt(j))) break; tmp++; j++; } // clear the hashset after each iteration hs.clear(); // save the maximum length max = Math.max(tmp, max); } 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
- Mac-安装gradle
- [Leetcode] 60. Permutation Sequence 解题报告
- yii2 常用ActiveForm表单样式用法总结
- 火星人永久家园建立在何处?
- python 3.4 error: Microsoft Visual C++ 10.0 is required(Unable to find)亲测解决办法
- Leetcode 3. Longest Substring Without Repeating Characters
- framebuffer_alloc()
- concurrent实现多线程的线程池开发
- 学习任何游戏引擎,编程语言,都应该进来看看
- 在spring中常被忽视的注解 @Primary
- Android/Java仿微信按时间长短分类显示时间戳
- Leetcode 76. Minimum Window Substring
- Ionic javascript Api | ion-view 视图的生命周期及事件集合
- Android 回调接口