[LeetCode]Longest Substring Without Repeating Characters题解

来源:互联网 发布:期货分钟数据下载 编辑:程序博客网 时间:2024/06/16 08:24

Longest Substring Without Repeating Characters:

Given a string, find the length of the longest substring without repeating characters.

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.

刚刚看到这道题的时候还是比较难受的,因为左思右想也想不到解法。

O(n^2)算法复杂度的程序会超时,所以需要想出一种O(n)的方法得到最大子字符串。

看了一下LeetCode的discuss上,O(n)的方法基本思路都是一样的。

class Solution {public:    int lengthOfLongestSubstring(string s) {        //创建一个数组记录这个字符上一次出现的位置,初始化为-1        vector<int> charaterLastOccur(256 , -1);        int len= 0, left = -1;//left是子字符串开始的位置        for(int i = 0; i < s.size(); i++){            //当前字符上一次出现的位置在left右边(>left)的时候,更新left的位置            if(charaterLastOccur[s[i]] > left){                left = charaterLastOccur[s[i]];            }            //否则的话,更新res            //新字符串长度(i-left)有可能比之前记录的len大,所以也更新一下            else{                len = max(len, i - left);            }            //一定记得在循环最后面加上这句,记录(更新)当前字符出线的位置            charaterLastOccur[s[i]] = i;        }        return len;    }};

基本的思路都在注释里了,这里举个栗子巩固一下。

例如字符串“abcabcd“,当遍历完了前面的“abc”后,
1. 再遍历到“a”,因为a已经在left(=-1)后面出现过,所以left更新为a上次出现的位置0,此时从left后面到i就没有重复的字符啦(从left到i的字符串也是当前循环选定的符合条件的子字符串)
2. 再遍历到“b”,因为b已经在left(=0)后面出现过,所以left更新为b上次出线的位置1,
3. …

每次都有检查子字符串的长度并且把最大的保存下来,所以最后就得到了我们想要的无重复字符的最长子字符串的长度了。

阅读全文
0 0
原创粉丝点击