Given a string, find the length of the longest substring without repeating characters.
Have you met this question in a real interview?
Yes
Example
For example, the longest substring without repeating letters for
"abcabcbb" is "abc", which the length is 3.
For
"bbbbb" the longest substring is "b", with the length of 1.
Challenge
O(n) time
public class Solution {
/**
* @param s: a string
* @return: an integer
*/
public int lengthOfLongestSubstring(String s) {
// write your code here
boolean[] record = new boolean[256];
int maxLen = 0;
int start = 0;
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if(record[c]){
maxLen = Math.max(maxLen, i - start);
for(int j = start; j < i; j++){
if(c == s.charAt(j)){
start = j + 1;
break;
}
record[s.charAt(j)] = false;
}
}
record[c] = true;
}
maxLen = Math.max(maxLen, s.length() - start);
return maxLen;
}
}
No comments:
Post a Comment