最长无重复子串

来源:互联网 发布:ios 数组转json字符串 编辑:程序博客网 时间:2024/05/21 16:28

Examples:

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

解题思路:
从首字母开始遍历计算以每一个字母结尾的最长无重复子串的长度。

  int lengthOfLongestSubstring(string s) {        vector<int> dict(256, -1);        int maxLen = 0, start = -1;        for (int i = 0; i != s.length(); i++) {            if (dict[s[i]] > start)                start = dict[s[i]];            dict[s[i]] = i;            maxLen = max(maxLen, i - start);        }        return maxLen;    }  

申请一个足够大的空间dict来存储已遍历字符的序号,如有重复字符,则存储最大序号。假设字符串”webkecba”,dict[s[i]] > start(start为-1或者前一对重复数组的第一个字符序号),表示在前一对重复字符的第一个字符之后有与s[i]重复的字符。该程序的时间复杂度为O(n)。

原创粉丝点击