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.
Solution:
Tips:
1. a table to record if a character was visited.
2. a value to record if character is expired.
This idea is similar with slid window of TCP/IP.
Java Code:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int maxLength = 0;
// here, regard 1 as array first element
int beginIdx = 1;
int[] charTable = new int[256];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int idx = i + 1;
if (charTable[c] >= beginIdx) {
beginIdx = charTable[c] + 1;
}
maxLength = Math.max(maxLength, idx - beginIdx + 1);
charTable[c] = idx;
}
return maxLength;
}
}