Shirlies 宁静专注认真的程序媛~

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.

 1 #define MAX_LETTER_NUM 255
2 class Solution {
3 public:
4     int lengthOfLongestSubstring(string s) {
5         if(s.empty())
6         {
7             return 0;
8         }
9
10         bool exist[MAX_LETTER_NUM];
11         int position[MAX_LETTER_NUM];
12         int index,rangeIndex;
13         int maxLen = 0;
14         int start = 0;
15
16         for(index = 0; index < MAX_LETTER_NUM; ++ index)
17         {
18             exist[index] = false;
19             position[index] = 0;
20         }
21
22         for(index = 0; index < s.size(); ++ index)
23         {
24             if(exist[s[index]])
25             {
26                 for(rangeIndex = start; rangeIndex <= position[s[index]]; ++ rangeIndex)
27                 {
28                     exist[s[rangeIndex]] = false;
29                 }
30                 start = position[s[index]] + 1;
31                 exist[s[index]] = true;
32             }else
33             {
34                 exist[s[index]] = true;
35                 maxLen = (maxLen < index - start + 1) ? index - start + 1:maxLen;
36             }
37
38             position[s[index]] = index;
39         }
40
41         return maxLen;
42     }
43 };
View Code

posted on 2016-08-04 14:47  Shirlies  阅读(352)  评论(0编辑  收藏  举报