leetcode-【中等题】3. Longest Substring Without Repeating Characters

题目:html

Given a string, find the length of the longest substring without repeating characters.ide

Examples:spa

Given "abcabcbb", the answer is "abc", which the length is 3.code

Given "bbbbb", the answer is "b", with the length of 1.htm

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.blog

连接https://leetcode.com/problems/longest-substring-without-repeating-characters/leetcode

答案:字符串

参考了这个连接后才明白解题思路,而后依据本身的理解写了代码。get

大体思路是:从当前字符开始,往前看,没有出现太重复字符的字符串string

代码:

 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
相关文章
相关标签/搜索