Leetcode:Longest Substring Without Repeating Characters 不含重复字符的最长子串

戳我去解题

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.

 

网上有一张图非常直观,借用一下:

Leetcode:Longest Substring Without Repeating Characters 不含重复字符的最长子串

从左往右扫描,当遇到重复字符时,以上一个重复字符的index+1 作为新的搜索起始位置,直到最后一个字符,复杂度为O(n)

class Solution {

public:

    int lengthOfLongestSubstring(string s) {

        const int nLetters = 256;

        std::vector<int> vec(nLetters, -1);

        int maxLen = 0;

        int curLen = 0;

        for (int i = 0; i < s.size(); ++i) {

            if (vec.at(s.at(i)) == -1) {

                ++curLen;

                maxLen = std::max(maxLen, curLen);

                vec.at(s.at(i)) = i;

            } else {

                i = vec.at(s.at(i));

                curLen = 0;

                std::fill(vec.begin(), vec.end(), -1);

            }

        }

        return maxLen;

    }

};

 

注意两点:

1. 这里字符包括各种大小写,数字符,还有&^*@#@这类的......所以索性搞个256的数组记录字符上次出现的位置

2. 尽量使用vector等c++容易,当使用vector 和 string 索引下标时 使用 at函数而不是 使用[]  前者有下标检查,可以各种防越界

你可能感兴趣的:(substring)