LeetCode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:交易软件 编辑:程序博客网 时间:2024/06/05 03:32

  • 题目
  • 题解
  • 优化

【题目】

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.

题解

这道题大意是找一个字符串中最长的没有重复字符的字符串。

我的解法比较普通,就是遍历字符串,利用string库的find函数,用一个sub记录没有重复字符的子字符串。代码如下:

int lengthOfLongestSubstring(string s){    string sub = "",max="";    for(int i = 0;i<s.size();i++){        if(sub.find(s[i]) != s.npos){            max = sub.size()>max.size()? sub : max;            i = i-sub.size()+1;            sub = "";        }        sub+=s[i];    }    max = sub.size()>max.size()? sub : max;}

优化

用自己的办法实现过后,在LeetCode的discussion上看到一个更快速的办法,跑leetCode测试用例,使用了22ms(上面的代码用了75ms)。其原理如下:

我们知道,被查找字符串使用的字符都是ASCII码,所以遍历这个字符串的时候,用一个大小为256的vector,记录字符串中每个字符在字符串中最后一次出现的的下标,比如dict['a']会被识别为dict[97]。

代码如下:

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;}

当然,如果我们可以假设,字符串是由a-zA-Z组成,这样,vector的长度可以够更少。

0 0
原创粉丝点击