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.

  意思就是:给出一个字符串,找出不包含重复字母的最长字串,输出字符串的长度。

  之前我一直是暴力破解,最近看到一个有意思的思路,记录下来。

  先上代码:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);//ASCCI hash
        int maxLen = 0, start = -1;
        for(int i = 0; i < s.size(); ++i)
        {
            if(dict[s[i]] > start)
            {
                start = dict[s[i]];
            }
            dict[s[i]] = i;
            maxLen = max(maxLen, i-start);
        }
        return maxLen;
    }
    int max(int a, int b)
    {
        return a > b ? a : b;
    }
};

  看到这么短的代码,我也被其优雅所折服,我们来看下思路:

  * 对字符串进行一次遍历,用一个大小为256(ascii最多有256种字符)数组记录每个字母最后一次的下标。
  * 如果当前字符在之前出现过就覆盖原来的数组元素,并且更新start值。
  * 每次循环时检查当前下标i-开始下标start和一个记录当前最大串长度的max变量的关系,将max保持或更新。
  * 需要注意的是,我更新start和max是在检测到重复字母时进行的,而最后一个字符不一定和前边重复,所以循环外要附加一次更新max的操作。

原文地址:https://www.cnblogs.com/jian-99/p/8940353.html