美文网首页
常见算法:最长子串

常见算法:最长子串

作者: yanlong107 | 来源:发表于2021-06-07 19:35 被阅读0次

题目1:

1、给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度

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()) {
                // 重新记录下标位置
                startIndex = max(startIndex, charMap[tmp] + 1);
            }
            charMap[tmp] = i;
            res = max(res, i - startIndex  +1);

        }

        return res;

    }
};

tips:
只遍历一次,时间复杂度 O(n)

相关文章

网友评论

      本文标题:常见算法:最长子串

      本文链接:https://www.haomeiwen.com/subject/fpcyrltx.html