The main idea of the title: Find the longest substring of a given string, requiring no repetition of characters in the substring. The difference between a substring and a subsequence is that a substring must be composed of consecutive characters, while a subsequence allows characters to be interrupted.
Topic Analysis:
Use num[i] to represent the longest substring ending with the character s[i]. We only need to scan the pointer forward from i and stop counting if there are repeated characters. The obtained value is the longest substring ending with s[i]. The length of the string. The time complexity is O(n^2)
Code display:
class Solution { public: int lengthOfLongestSubstring(string s) { int len = s.length(); bool visit[256]; memset(visit,0,sizeof(visit)); int count = 0; int max = 0; for(int i=0;i<len;i++){ for(int j=i;j>=0;j--){ if(!visit[s[j]]){ count++; visit[s[j]] = 1; } else break; } if(count>max) max = count; memset(visit,0,sizeof(visit)); count = 0; } return max; } };
The second solution is that the longest substring is s[start,...,i], and the length of the substring can be returned. The point is that start and i change dynamically in one loop. For example, s="abcabcbb".
First, start points to -1 position, i is 0 position, pos['a']=0, return length i-start=1;
Then i=1, there is no repetition, start does not change, pos['b']=1, return i-start=2;
Then i=2, there is no repetition, start does not change, pos['c']=2, return i-start=3;
Then i=3, there is a repetition, start is moved back, start = pos['a'] = 0, update pos['a'] = 4, return i-start=3 …
Why is start moved backwards here? Because the substring is required to be non-repetitive, if the start is not moved backward, it must be abca, and there is a repeated a. Therefore, once there is a repetition, it must be moved backward by start, and then moved to the position where a appeared for the first time.
Code display:
class Solution { public: int lengthOfLongestSubstring(string s) { int maxlen = 0; int pos[256]; memset(pos,-1,sizeof(pos)); int start = -1; for(int i=0;i<s.length();i++){ if(pos[s[i]]>start) start = pos[s[i]]; pos[s[i]] = i; maxlen = max(maxlen,i-start); } return maxlen; } };