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.
只扫描一遍字符串s的解法,即时间复杂度为O(n),代码如下:
public class Solution { public int lengthOfLongestSubstring(String s) { int start = 0; Map<Character,Integer> map = new HashMap<Character,Integer>(); int max_length = 0; int size = s.length();//字符串长度 for(int i=0;i<size;i++) { char c = s.charAt(i); if(map.containsKey(c)) { int sub_length = i-start; max_length = sub_length>max_length?sub_length:max_length; int index = map.get(s.charAt(i));//之前出现过c的位置 //将start到index所有字符从map中删除 for(int j=start;j<=index;j++) { map.remove(s.charAt(j)); } map.put(c,i); start = index+1;//更新start } else { map.put(c,i); if(i==size-1) max_length = map.size()>max_length?map.size():max_length; } } return max_length; } }
问题关键是如何在常量时间内判断当前字符是否在字串中出现过,必须用到一个hashmap。如果直接使用String 的contains方法会导致效率过低,limit time exceed。