O(n)
https://leetcode.com/problems/longest-substring-without-repeating-characters public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() <= 0) {
return 0;
}
int[] visited = new int[256];
for (int i = 0; i < 256; i++) {
visited[i] = -1;
}
int start = 0;
int end = 0;
int len = s.length();
int retval = 1;
while (end < len) {
char ch = s.charAt(end);
if (visited[ch] >= 0) {
// current char is visited so far
int currLen = end - start;
if (currLen > retval) {
retval = currLen;
}
int k = visited[ch];
for (int i = start; i <= k; i++) {
visited[s.charAt(i)] = -1;
}
start = k + 1;
} else {
// current char is not visited so far
if (end == len - 1) {
// reach the end of the string
int currLen = end - start + 1;
if (currLen > retval) {
retval = currLen;
}
}
}
visited[ch] = end;
end ++;
}
return retval;
}
}