Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.code
Examples:字符串
Given "abcabcbb", the answer is "abc", which the length is 3.get
Given "bbbbb", the answer is "b", with the length of 1.string
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.it
1.解题思路io
本题借助HashMap实现。
1) 若是字符未出现过,则put(字符,index);
2) 若是字符出现过,则维护len=上次出现的index-遍历的起始点。
那问题就到了如何去定义遍历的起始点呢,咱们固然能够从0开始,而后每次加1,可是经过下面的例子,咱们很容易就发现这样会有不少状况冗余:
“abcdecf”
咱们从index 0开始,到第二个字符c-index5,咱们会发现已经存在,因此len,5-0=5;但若是咱们以后index从1开始,咱们会发现必然还会在index5这边中止,为了减小这种冗余,咱们想到能够在一次重复后,将start置为重复元素Index+1,这里就是index3-d, 这样咱们在碰到已经存在的字符时,就要再加上一个判断,看其上一次出现是否在start以前,若是在start以前,则不做考虑,直接Put进新的位置;若是是在start以后,则就代表确实遇到了重复点。
注意点:
1)每次都要更新字符的位置;
2)最后返回时,必定要考虑到从start到s.length(字符串末尾)都没有遇到重复字符的状况,所欲须要比较下maxLen和s.length()-start的大小。class
2.代码遍历
public class Solution { public int lengthOfLongestSubstring(String s) { if(s.length()==0) return 0; HashMap<Character,Integer> hm=new HashMap<Character,Integer>(); int start=0; int maxLen=1; for(int i=0;i<s.length();i++){ if(hm.containsKey(s.charAt(i))&&hm.get(s.charAt(i))>=start){ int len=i-start; maxLen=Math.max(maxLen,len); start=hm.get(s.charAt(i))+1; } hm.put(s.charAt(i),i); } return Math.max(maxLen,s.length()-start); } }