No repeated character string of the longest sub Leetcode

Title Description

Given a string, you find out which does not contain a sub-length of the longest string of repeated characters.

Thinking

+ Double hash pointer: Hash define a position of the character appears to hold the definition begin indicates the starting substring, count to represent the length of the substring

Traversing the string, if the character has appeared, then begin to adjust the position max (position +1 begin, the last character that appears), If it is not, then the shelf life Hash position, count ++. Explained as follows:
Example: wobgrovw
I = 0, W forward, does not appear to save Hash position calculating COUNT;
I =. 1, O intake, does not appear to save Hash position calculating COUNT;
I = 2, B feed, does not appear, Hash save location, calculate COUNT;
...
i = 5, o forward, has appeared, this time begin to 0, we should say to begin adjusting the position 2, that is, the next occurrence of a time o, the starting point is adjusted to b
...
i = 8, w intake, has occurred, this time to begin 2, however, the position of the last occurrence w begin before, does not affect

Code

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.size() == 0)
            return 0;
        if (s.size() == 1)
            return 1;
        vector<int> Hash(128, -1);
        int count = 0;
        int Max = 0;
        int begin = 0;
        for (int i = 0; i < s.size(); i++)
        {
            if (Hash[s[i]] != -1)
            {
                begin = max(begin,Hash[s[i]] + 1);
            }
            Hash[s[i]] = i;
            count = i - begin + 1;
            if (count > Max)
                Max = count;
        }
        return Max;
    }
};
Published 85 original articles · won praise 0 · Views 383

Guess you like

Origin blog.csdn.net/weixin_38312163/article/details/104981935