LeetCode-3. Longest Substring Without Repeating Characters
来源:互联网 发布:caffe 深度学习 编辑:程序博客网 时间:2024/05/02 01:15
Given a string, find the length of the longest substring without repeating characters. For example, 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.
这道题仔细想想其实不难的,最坏情况下,也就是所有都不重复的,时间复杂度会达到N平方。
最开始忘了加上break,导致超时~
后来上网看了一个帖子提供的思路 点击打开链接
发现和我的思想是一样的,回来看看忘了加break,在运行~就Ok~ 不过再仔细想想,还是他的更快一点。
public class Solution { public int lengthOfLongestSubstring(String s) { int count = 0; int max=0; HashSet<Character> set = new HashSet<Character>(); for(int j = 0 ; j<s.length(); j++){ for(int i = j ; i<s.length(); i++){ if(set.contains(s.charAt(i))){ if(count>max){ max=count; } set.clear(); count = 0; break; // } else{ set.add(s.charAt(i)); //System.out.println(count); count++; } } } if(count>max){max=count;}return max; }}
这是我最开始的速度
后来按照博客中的方法改进了一下,于是....
人家的复杂度是N啊,好厉害
这是修改后的代码,主要改进在于循环加一后不用再重新寻找大部分不重复的子字符串。
public class Solution { public int lengthOfLongestSubstring(String s) { int count = 0; int max=1; boolean[] flags = new boolean[256]; int start=0; int end=0; if(s.length() ==0) return 0; while(end < s.length()){ if(flags[s.charAt(end)] == false){ flags[s.charAt(end)] = true; end++; }else{ flags[s.charAt(start)] = false; count = end - start; if(count>max){ max=count; } start++; } } count = end - start;if(count>max){max=count;}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
- CAShapeLayer简介
- clion jiqiao
- Bzoj4034:[HAOI2015]T2:树链剖分
- 创建线性表,以及表中的基本操作
- android studio 的一个坑
- LeetCode-3. Longest Substring Without Repeating Characters
- 受限Boltzmann机(Restricted Boltzmann Machine)
- NYOJ38-布线问题
- android 判断系统是否有Navigation Bar
- 选择cocos2d-js的原因,摘录了官网的一些东西
- [查异常网]-20160401-清除代码异味
- POJ 3544
- LAMPP Run PHP
- Android MTK 锁屏图片和背景墙纸的修改