题目:Longest Substring Without Repeating Characters
描述: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.
思路:maxlength,length初始化为1。将字符串str转换为字符数组strArr,在申明hashmap对字符位置进行定位,用i与j两个索引对数组进行一次遍历。
当字符strArr[j]第一次出现或者hashmap(strArr[j])<i(此时i已经在strArr[j]的前面),length加1并将strArr[i]作为key存入hashmap中,值为索引值j,j向后移动。
如果不满足,则表明遇到重复值。将i向前增1。重置length值为j-i+1
注意点1.边界条件 字符串长度为1或者为空的时候单独处理。
2.hashmap中,在i之前位置的字符不纳入重复判断。
public class Solution {
public int lengthOfLongestSubstring(String s) {
char[] tem = s.toCharArray();
HashMap<Character,Integer> map = new HashMap<Character,Integer>();
int maxlength = 1;
int length = 1;
int i=0;
int j=1;
if(tem.length == 0){
return 0;
}
if(tem.length == 1){
return 1;
}
map.put(tem[0],0);
while(true){
if(!map.containsKey(tem[j])||map.get(tem[j])<i){
length++;
if(length>maxlength){
maxlength = length;
}
}else{
i=map.get(tem[j])+1;
length = j-i+1;
}
map.put(tem[j],j);
j++;
if(j>=tem.length){
break;
}
}
return maxlength;
}
}