Longest Substring Without Repeating Characters

来源:互联网 发布:网络储备人才招聘 编辑:程序博客网 时间:2024/06/07 01:29

题目描述

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.


解题思路与分析

该题目难度一般,最简单的思路是把某个字母在ASCII码表对应的数字作为一个数组的下标,数组存储的数字代表的是下标所对应的字母出现的次数,从第i位开始遍历字符串,判断条件就是数组下标对应字母出现的次数不能大于等于两次,如果判断条件不成立,那么就将该下标赋值给外层循环变量i。但这种方法需要用到双层循环,时间复杂度比较高,不是很可取。

另一个比较好的解题思路切入点是用数组或vector记录每个元素曾出现的下标,初始为-1,这里为方便起见,我选用vector,int型变量start用来记录子字符串的起始位置下标,而这个子字符串的判断标准同样是看母字符串某元素对应的下标,如果下标为-1,那就说明该字母还没有出现过,如果它的下标不为0,说明该字母在前面出现过,那么此时就将该字母对应的下标赋值给start,依次遍历下去,每一次遍历都要比较该子字符串的长度和最大长度。
说了这么多,还是不如代码来的直接hhh。


C++代码实现

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

反思与总结

不能每道题都用最初笨重而繁琐的方法,有时候考虑问题再深入一些,思想上一个小的转变可能对于时间复杂度就是一个很好的缩减!

原创粉丝点击