Leetcode Note: Longest Substring Without Repeating Characters
I. 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.
Ii. Question Analysis
The general idea is to give a string, find the longest string without repeated characters, and output its length. You can use two pointers, one pointing to the header of the current substring, And the other pointing to the tail. The tail pointer continuously scans back. When there is a character before, record the comparison results between the length of the current substring and the optimal solution. Then, the header pointer is continuously scanned until a character is scanned and the tail pointer is the same. Then, the tail pointer continues scanning. When the tail pointer reaches the end of the string, the algorithm ends. Algorithm complexity O (n) + O (n) = O (n ).
Iii. Sample Code
class Solution {private: bool canUse[256];public: int lengthOfLongestSubstring(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function memset(canUse, true, sizeof(canUse)); int count = 0; int start = 0; int ret = 0; for(int i = 0; i < s.size(); i++) { if (canUse[s[i]]) { canUse[s[i]] = false; count++; } else { ret = max(ret, count); while(true) { canUse[s[start]] = true; count--; if (s[start] == s[i]) break; start++; } start++; canUse[s[i]] = false; count++; } } ret = max(ret, count); return ret; }};
Iv. Summary
Reference: http://www.cnblogs.com/remlostime/archive/2012/11/12/2766530.html