Longest Substring Without Repeating Characters

来源:互联网 发布:kahn算法 编辑:程序博客网 时间:2024/06/05 03:29
Given a string, find the length of the longest substring without repeating characters.
For example:
1.The longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
2.For "bbbbb" the longest substring is "b", with the length of 1.
算法主要用一个映射表记录现在已遍历到的字符,并将相应的索引记录下来。用一个起始索引变量记录字符串的开始索引位置,遇到重复字符(且该重复字符的索引值>=开始索引)时更新该索引,将其变为重复变量索引的后一位,并更新最大字符串长度。最后别忘了从开始索引到最后还没出现重复字符的情况。
startIndex:不包含重复字符的字符串开始索引,起始为0
maxLength:用于记录最长的非重复字符的字符串长度,起始为0
对于例1:主要信息随着遍历的改变情况如下

字符串

a

b

c

a

b

c

b

b

索引

0

1

2

3

4

5

6

7

a

0

0

0

3

3

3

3

3

b

 

1

1

1

4

4

6

7

c

 

 

2

2

2

5

5

5

startIndex

0

0

0

1

2

3

5

7

maxLength

0

0

0

3

3

3

3

3

class Solution {public:int lengthOfLongestSubstring(string s) {int maxLenght = 0;           //最长非重复字串长度int startIndex = 0;          //每次出现重复时更新开始索引map<char, int> record;       //用于记录字符出现索引的映射表for(int i=0;i<s.size();++i){if (record.count(s[i])>0&&record[s[i]]>=startIndex) //存在字符记录且索引不比开始索引小{maxLenght = max(maxLenght,i-startIndex);startIndex =record[s[i]]+1;   //出现重复字符,将开始索引更新为重复字符的后一位}record[s[i]] = i;}maxLenght = max(maxLenght,(int)s.size()-startIndex);return maxLenght;}};


0 0
原创粉丝点击