GLZ free form of title LeetCode brush Note 3

3. No repeating characters longest substring

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

示例 1:
输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。

Please note that your answer must be a substring of length, "pwke" is a sub-sequence, not a substring.

Topic solution

First thought, if this question is not repeated characters, so happy, it can direct the output string length. The problem arises in a repeat of the string body. We have to consider is, when there is repeated characters, we let a character which "exist" in our sub-strings, allows maximum string length.
Therefore, we only need to maintain two head and tail pointer to the beginning and end of the longest possible substring. Are determined at each movement of the pointer does not exceed the currently known lengths longest length exceeds the maximum length is updated.
Specific update method: storing a character string appearing in the current sub-use hash tables Traversal string tail node, the end node determines whether the character appeared. If it does, then the mobile node to the head end of the string after a node in a sub-location, and eliminates the hash table since the mobile node and no longer in the head substring of characters recorded.

Code

This problem using c ++

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        bool hashmap[256];
        for(int i = 0; i < 256;i++)
        {
            hashmap[i] = 0;
        }
        int tail = 0,head = 0;
        int max_len = -1;
        for(tail = 0; tail < s.length();tail++)
        {
            if(tail - head + 1 > max_len)
            {
                max_len = tail - head;
            }
            if(hashmap[int(s[tail])])
            {
                while(s[head] != s[tail])
                {
                    hashmap[int(s[head])] = 0;
                    head++;
                }
                head++;
            }
            hashmap[int(s[tail])] = 1;
        }
        if(tail - head  > max_len)
        {
            max_len = tail - head;
        }
        return max_len;
    }
};
Released seven original articles · won praise 2 · Views 365

Guess you like

Origin blog.csdn.net/qq_37477357/article/details/89468260