码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Algorithm 03

时间:2015-03-21 21:12:41      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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.

Tags: Hash Table, Two Pointers, String

 

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         //从前往后开始,后面一旦碰到『当前字符串中』前面出现过的字符,则直接跳到前面那个重复字符的下一个字符开始新字符串统计。
 5         //既然是比较当前字符串,必须要有一个值来保存当前字符串从什么位置之后开始。可以初始化一个int curSubStartPosPre = -1表示
 6         //一开始是从-1后面也就是0开始统计的,字符串长度就是后面的index-(-1),如1-(-1)=2表示当前字符串长度达到了2。
 7         
 8         //重复出现的判断方法:构建一个以字符为键的数组,因为字符不超过256,可构建int lastAppearPos[256],存储每个字符上一次
 9         //出现的位置,当扫描到一个字符时,查看数组中对应值lastAppearPos[字符],如果大于curSubStartPosPre,说明这个字符上一次
10         //出现位置在当前字符串中,也就意味着当前字符串出现重复。
11         
12         //随着字符的移动,当前的长度为index-curSubStartPosPre。保存一个max来表示最大值,如果当前长度大于max则更新max。
13         
14         //lastAppearPos[256]:本来是index对应字符,现在以字符为下标对应index,完成hash table的构建。因为直接比较的是字符,
15         //用hash table可以实现o(1)的复杂度。
16         
17         int curSubStartPosPre = -1;
18         int lastAppearPos[256];
19         int max=0;
20         memset(lastAppearPos, -1, sizeof(lastAppearPos));
21         int i=0;
22         while(i<s.length()){
23             if(lastAppearPos[s[i]] > curSubStartPosPre){
24                 curSubStartPosPre = lastAppearPos[s[i]];
25             }
26             if(i-curSubStartPosPre > max){
27                 max = i-curSubStartPosPre;
28             }
29             
30             lastAppearPos[s[i]] = i;
31             i++;
32         }
33         return max;
34         
35     }
36 };

 

 

LeetCode Algorithm 03

标签:

原文地址:http://www.cnblogs.com/chen0958/p/4356110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!