首页 > 代码库 > leetcode 3 Longest Substring Without Repeating Characters

leetcode 3 Longest Substring Without Repeating Characters

public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLen = 0;
int maxLenTmp = 0;
Map<Character, Integer> map = new HashMap<Character, Integer>(
s.length() / 2);
char[] ss = s.toCharArray();

int times = ss.length;
int start = 0;
for (int i = 0; i < times; i++) {

char a = ss[i];
if (map.containsKey(a)) {
if (maxLenTmp > maxLen) {
maxLen = maxLenTmp;
}

int end = map.get(a);
for (int j = start; j <= end; j++) {

map.remove(ss[j]);
maxLenTmp --;
}
i --;
start = end + 1;

continue;
} else {
map.put(a, i);
maxLenTmp++;
}

if (i == times - 1) {
if (maxLenTmp > maxLen) {
maxLen = maxLenTmp;
}
}


}
return maxLen;
}
}

技术分享

leetcode 3 Longest Substring Without Repeating Characters