Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
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.
Subscribe to see which companies asked this question
这一题题意比较简单,能马上明白意思,由于做过第一天的题目,所以马上想到了利用map的数据结构特性,把下标和字符结合起来,并利用map的唯一性的特点,进行数据的保存。
一开始思路虽然对了,跟top solution一样,但是提交了很多次都没过,因为还有很多小细节处理有问题。比如对max的更新一开始放到了 containkey中,后来发现不行,因为如果都没有重复的字符串,max就为0。然后换了思路,每次循环都更新max,记录第一个重复的字符的下标。但是在得到的方式有问题,如果只是单纯的赋值是有问题的,因为map上一次数据除了重复的处理了,其他数据依旧保存的,所以要进行max处理,取最大值,并且firstIndex这个值英国是取自身和重复字符下标值+1两者的最大值。
public static int lengthOfLongestSubstring(String s){
if(null==s || s.length()==0){
return 0;
}
HashMap<Character,Integer> pair=new HashMap<>();
int max=0,tmpLength,firstIndex=0;
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
//如果已经存在了,则取value(即其对应的下标)
if(pair.containsKey(c)){
//防止因为map旧数据没有更新,导致长度错误
firstIndex=Math.max(firstIndex,pair.get(c)+1);
}
pair.put(c,i);
max=Math.max(max,i-firstIndex+1);
}
return max;
}
提高代码质量就是:积累精美的思路,优质的细节的过程。