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 subsequenceand not a substring.
题意:
给定一个字符串, 求其中无重复字母的最长子串
Solution1:
maintain a sliding window [start...i], making sure that each char in such window, its frequency is 1 (without Repeating chars)
when one char's frequency > 1, there is repeating char, then move pointer start to find the next window
code:
/*
Time Complexity: O(n)
Space Complexity: O(256)
*/
class Solution {
public int lengthOfLongestSubstring(String s) {
// corner case
if( s == null || s.length() == 0) return 0; int[] map = new int[256];
int result = 0;
int start = 0;
for(int i = 0; i < s.length(); i++){
map[s.charAt(i)] ++;
if(map[s.charAt(i)] > 1){
while(map[s.charAt(i)] > 1){
map[s.charAt(start)]--;
start++;
}
}
result = Math.max(result, i - start + 1);
}
return result;
}
}