Longest Substring Without Repeating Characters
来源:互联网 发布:数据库系统实现 公开课 编辑:程序博客网 时间:2024/05/19 18:44
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.
最直接解决办法就是设置两个指针扫描字符串,如果碰到重复的跳到外循环下一个位置继续扫描,这样复杂度为O(n^2),简单动手发现这种实现做了很多重复工作。后面进行优化。
import java.util.Hashtable;public class Solution { public int lengthOfLongestSubstring(String s) {int MaxLen = 0;Hashtable<Character, Integer> tb = new Hashtable<>();int count = 1;for(int i=0;i<s.length();i++){tb.clear();tb.put(s.charAt(i), 1);count = 1;for(int j=i+1;j<s.length();j++){if(!tb.containsKey(s.charAt(j))){tb.put(s.charAt(j), 1);count ++ ;}else {break;}}if(count > MaxLen){MaxLen = count;}}return MaxLen;}}
优化时间复杂度的方法:我们可以考虑只扫描母串,直接从母串中取出最长的无重复子串。
对于s[i]:
1.s[i]没有在当前子串中出现过,那么子串的长度加1;
2.s[i]在当前子串中出现过,出现位置的下标为j,那么新子串的起始位置必须大于j,为了使新子串尽可能的长,所以起始位置选为j+1。
public int lengthOfLongestSubstring2(String s){int maxLen = 0;//记录子串前一位置的下标,初始为-1int index = -1;//记录字符在s中出现的位置。int [] loca = new int[256];Arrays.fill(loca, -1);for(int i=0;i<s.length();i++){char c = s.charAt(i);//如果c出现了,更新index 为c上一次出现位置if(loca[c] > index){index = loca[c];}// 更新最大长度if(i-index>maxLen){maxLen = i-index;}loca[c] = i;}return maxLen;}
时间对比如下图:
0 0
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- 安卓中遮罩图片的处理
- NTP
- 模拟量I/O与数字量I/O有什么区别?
- 【quick-cocos2d-x】开发工具sublime text及其强力插件QuickXDev
- poj题目分类
- Longest Substring Without Repeating Characters
- 整理了一个多数据库通用操作类
- Sublime设置特殊缩进
- Git Push 避免用户名和密码方法
- SQL Server 2008 R2数据库镜像部署
- mvn报错:No goals have been specified for this build
- fedora20 安装搜狗输入法及各种问题的解决
- Flynn Architecture Note
- Java 并发编程之线程安全性