问题链接
Longest Substring Without Repeating Characters
问题描述
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.
解决办法
public class Solution {
public int lengthOfLongestSubstring(String s) {
int lp = 0;
String sp = "";
while (s.length() > 0) {
String a = Character.toString(s.charAt(0));
s = s.substring(1);
int j = sp.indexOf(a);
if (j > -1) {
lp = Math.max(lp, sp.length());
sp = sp.substring(j + 1) + a;
} else {
sp += a;
}
}
return Math.max(lp, sp.length());
}
}
然而这个解法太慢,最长的测试用例需要的时间为300ms
左右,gg
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max=0;
for (int i=0, j=0; i<s.length(); ++i){
if (map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-j+1);
}
return max;
}
}