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
原创粉丝点击