leetcode(三)—— Longest Substring Without Repeating Characters(最长不重复子串 Python/C++)

Longest Substring Without Repeating Characters | LeetCode OJ

使用 hash

判重问题首先想到的就是 hash(或者使用 map);

思路:遍历全部子串(n+(n-1)+…+1=n(n+1)/2),设置一个最大长度变量跟踪更新最大长度。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s == "") return 0;
        size_t maxlen = 0, maxidx = 0;
        char buf[256] = { 0 };
        for (size_t i = 0; i < s.size(); ++i)
        {
            memset(buf, 0, sizeof buf);
            size_t j;
            buf[s[i]] = 1;
            for (j = i + 1; j < s.size(); ++j)
            {
                if (buf[s[j]] == 0)
                    buf[s[j]] = 1;
                else
                {
                    if ((j - i) > maxlen)
                    {
                        maxlen = j - i;
                        maxidx = i;
                    }
                    break;
                }
            }
            if (j == s.size() && (j - i) > maxlen)
            {
                maxlen = j - i;
                maxidx = i;
            }
        }
        return maxlen;
    }
};

你可能感兴趣的:(leetcode)