3. Longest Substring Without Repeating Characters
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.
Subscribe to see which companies asked this question
1.mine (16ms/40.58%)
int lengthOfLongestSubstring(char* s) {
int j,ph,pt,n,max=1;
if(s[0]=='\0'){
return 0;
}
if(s[0]=='\0'){
return 1;
}
ph=0;pt=0;
while(s[pt+1]!='\0'){
pt++;
for(j=ph;j<pt;j++){
if(s[pt]==s[j]){
ph=j+1;
}
}
n=pt-ph+1;
if(n>max){
max=n;
}
}
return max;
}
2.example(6ms/72.84%)
int lengthOfLongestSubstring(char* s) {
int maxLen = 0, prevMaxLen = 0, prevIndexOf[128];
bzero(prevIndexOf, sizeof(prevIndexOf));
for (char *c = s; *c; c++) {
int idx = c - s + 1; // Add 1 to the index since prevIndexOf is initialized with zeros
int candidateLen = idx - prevIndexOf[*c];
int curMaxLen = (++prevMaxLen < candidateLen) ? prevMaxLen : candidateLen;
prevIndexOf[*c] = idx;
if (curMaxLen > maxLen) {
maxLen = curMaxLen;
}
prevMaxLen = curMaxLen;
}
return maxLen;
}