LeetCode - Longest Substring Without Repeating Characters

来源:互联网 发布:linux 调用中文输入法 编辑:程序博客网 时间:2024/06/08 07:56

题目描述:

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.

刚看到这道题时感觉无从下手,直接求解会很麻烦,而且复杂度会很高。比较简单而且易理解的方法是用一个数组pos[128],记录每个字符上次出现的位置,当遍历字符串发现某字符时,检查其上次出现的位置,若其出现在当前子字符串起点start前,说明当前子字符串中该字符串只出现一次,不需要更改起点;若其出现在当前子字符串起点start之后,说明当前子字符串中该字符出现两次,因此更改起点start=pos[s[i]]+1,得到新的无重复字符的子字符串。依次遍历字符串一遍就能产生所有满足条件的子字符串,然后每次都对子字符串长度进行判断,保留最大的字符串长度即可。需要注意的是,start初始值为0,那么要将pos[128]的所有元素初始值为-1,这样才能保证在最开始的时候所有字符上一次出现的位置在当前子字符串起点之前。

class Solution {public:    int lengthOfLongestSubstring(string s) {        int start=0;        int maxLength=0;        int pos[128];        for(int i=0;i<128;i++)        {            pos[i]=-1;        }               for(int i=0;i<s.size();i++)        {        if(pos[s[i]]>=start)        {        start=pos[s[i]]+1;        }                if(maxLength<(i-start+1))        {        maxLength=i-start+1;        }        pos[s[i]]=i;        }            return maxLength;    }}; 



0 0