Longest Substring Without Repeating Characters
Description:
Given a string, find the length of the longest substring without repeating characters. 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.
Code:
int lengthOfLongestSubstring(string s) { if (s.size()==0) return 0; int pos[256]; memset(pos,-1,256*sizeof(int)); int start = 0,maxLen = 1; pos[s[0]] = 0; for (int i = 1; i < s.size(); ++i) { if (pos[s[i]] >= start) { if (i-start>maxLen) maxLen = i-start; start = pos[s[i]]+1; } else { if (i-start+1>maxLen) maxLen = i-start+1; } pos[s[i]] = i; } return maxLen; }
类似于求解最大和子序列