Skip to content

Instantly share code, notes, and snippets.

@bluesunxu
Created December 19, 2012 05:07
Show Gist options
  • Save bluesunxu/4334528 to your computer and use it in GitHub Desktop.
Save bluesunxu/4334528 to your computer and use it in GitHub Desktop.
Find longest sub string without duplicate character.
int lengthOfLongestSubstring(string s) {
if(s.empty()) return 0;
int len = s.length();
int arr[256];
for(int i=0; i<256; ++i)
arr[i] = -1;
int curStart = 0, curLen = 1;
int maxLen = 1;
for(int i=0; i<len; ++i) {
if(arr[s.at(i)] < curStart)
{
// current char shown before curStart
// update its index and update the curLen
arr[s.at(i)] = i;
curLen = i - curStart +1;
}
else {
// current char shown after the curStart
// it's a dup in the current string under investigation
// update the curLen, reset the curStart
curLen = i - curStart;
curStart = arr[s.at(i)] + 1;
arr[s.at(i)] = i;
}
if(maxLen < curLen)
maxLen = curLen;
}
return maxLen;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment