题解 | #最长不含重复字符的子字符串#
最长不含重复字符的子字符串
http://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7
使用哈希暴力求解:遍历字符串,把每个字符串放入哈希表中,如果哈希表中已经存在该字符,更新最大长度,并把下标回调。
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return int整型
*/
public int lengthOfLongestSubstring (String s) {
int max = 0;
Map<Character,Integer> map = new HashMap<>();
char ch [] = s.toCharArray();
for(int i=0;i<ch.length;++i){
if(map.get(ch[i])==null){
map.put(ch[i],i);
}
else {
max = Math.max(max,map.size());
i = map.get(ch[i]);
map.clear();
}
}
return Math.max(max,map.size());
}
}
查看8道真题和解析