current position:Home>Common algorithm: Longest substring

Common algorithm: Longest substring

2022-01-26 22:24:16 Yan Long

subject 1:

1、 Given a string , Please find out that there are no duplicate characters in it Longest substrings The length of

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int startIndex = 0;
        int res = 0;
        map<char,int> charMap;
        for (int i = 0; i < s.length(); i++) {
            char tmp = s.at(i);
            if (charMap.find(tmp) != charMap.end()) {
                //  Re record subscript position 
                startIndex = max(startIndex, charMap[tmp] + 1);
            }
            charMap[tmp] = i;
            res = max(res, i - startIndex  +1);

        }

        return res;

    }
};

tips: Just go through it once , Time complexity O(n)

copyright notice
author[Yan Long],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262224141702.html

Random recommended