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.
我自己覺得這道題還是很有難度的哈。
這個思路要展開來不難,都能很快想到要用HashMap。但是在算法的問題上就需要細致的思考了。
有幾個思考錯誤可能很多人會犯。比如說很多人第一個反應以為是求兩個重復的數之間的length。就以下面這組數來做例子。
1,2,3,4,5,6,2,7,8,3,9,0,8,7
很多人第一個反應就是要算2和2之間,3和3之間,7和7之間,8和8之間的length。
但是題目上并沒有說這種without repeating的length,首尾的前一位后一位必須一樣啊。這就是典型的誤區了。光顧著找重復的了。
這也是為什么在代碼中,Math.max()method在if statement外面的原因。
代碼如下。
public class Solution { public int lengthOfLongestSubstring(String s) { if(s.length()<2){ return s.length(); } HashMap<Character,Integer> map=new HashMap<Character,Integer>(); int len=s.length(); int end=1; int start=0; int max=1; map.put(s.charAt(0),0); while(end<len){ if(map.containsKey(s.charAt(end))&&map.get(s.charAt(end))>=start){ start=map.get(s.charAt(end))+1; //since it's for length,so need +1 } max=Math.max(max,end+1-start); //also for length,end +1 map.put(s.charAt(end),end); end++; } return max; }}新聞熱點
疑難解答