[leetcode]03 longest substring without repeating

来源:互联网 发布:英雄无敌3 数据修改 编辑:程序博客网 时间:2024/06/07 13:52

Description:

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.

Solution

class Solution {public:    int lengthOfLongestSubstring(string s) {        int len = s.size();        int max = 0;        int index[128] = { 0 };        if (len == 0)            return 0;        for (int j = 0,i = 0; j < len; j++)        {            if(i<index[s[j]])                i = index[s[j]];            //i = Math.max(index[s[j]], i );            if (max < j - i + 1)                max = j - i + 1;            //max = Math.max(j - i + 1, max);            index[s[j]] = j + 1;        }        return max;    }};

Discussion

首先,暴力解决肯定是可以的,但是可能会超时。脑子里第一个跳出来的想法就是暴力解决,用i,j记录不重复子串的头和尾,用max记录字串最长大小,从头到尾扫描。但是在中途会多次重复扫描,这样的效率比较低。

当然了,最好的办法肯定是从头到尾只扫描一次,那除了头和尾两个指针指向的字母,每次我们可以对比是否相等,但是我们如何记录其他出现过的字母呢?

所以在这里可以构建一个映射关系,用一个数组,将当前的字母和其在字符串中的位置存储起来,在每次遇到一个字母的时候,都保存其序号,当下次遇到一样的字母,这个位置就会被刷新,子串头部的位置就可以根据这个来变化,同时在过程中记录最长子串的位置。

赞美一下小可爱,昨晚耐心给我讲解。

阅读全文
0 0