Description
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
Two-pointers with Hashmap, O(n) time, O(n) space
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null) {
return -1;
}
boolean[] hasChar = new boolean[256]; // hasChar[c] means char c has appeared in current window
int winStart = 0;
int maxLen = 0;
for (int winEnd = 0; winEnd < s.length(); ++winEnd) {
char c = s.charAt(winEnd);
if (hasChar[c]) { // maintain chars between [winStart, winEnd] unique
while (s.charAt(winStart) != c) {
hasChar[s.charAt(winStart++)] = false;
}
++winStart;
}
hasChar[c] = true;
maxLen = Math.max(maxLen, winEnd - winStart + 1);
}
return maxLen;
}
}