LeetCode 之 Longest Substring Without Repeating Characters

来源:互联网 发布:乐器管子价格淘宝 编辑:程序博客网 时间:2024/05/28 22:12

i原题:

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。

这个题的解法其实主要在于数这个字符,比如abcda,则挨个数,数到最后一个a,则最长为abcd,为了检测某个字符是否在连续数组中出现,用一个数组保存就行,由于每个字符其实都是一个int,而其数组中的内容就是这个字符在字符串中的出现的位置。

1 对这个字符串进行扫描,如果这个字符第一次出现,即record[i]=-1,否则就是出现过,而且record保存的是字符在字符串中出现的最后一个的位置(KEY)

2 如果这个字符出现过,那么当前的最长子串有两种可能

    1)  abcda tempMax 的长度为bcda,即4 (两个a之间的长度)

    2)    abcdefgdc  tempMax的长度为cdefg   (不是两个c之间的长度,而是c和第一个d之间的长度,这就是start是start和record[current]的max的原因

如图


用一个start表示一个不含有重复字符的字符串的开始位置,i表示现在字符的位置,用i减去现在的start就是长度了,记得及时更新max

代码如下(120ms):

class Solution {public:    int lengthOfLongestSubstring(string s) {        //int record[256] = {-1};        vector<int>record(256,-1);        int result = 0;        int start = 0;        int tempMax = 0;                for(int i = 0; i< s.length();i++){            int current = s[i];            if( record[current] == -1 ){                record[current] = i;                tempMax++;            }            else            {                               start = max(start , record[current]);                                tempMax = i-start;                                record[current]=i;                        }            result = max(result,tempMax);        }        return result;                    }        };

0 0
原创粉丝点击