aiheshan

有多自律,才能有多自由

导航

leetcode 3. Longest Substring Without Repeating Characters

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

 

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.

 

思路:因为字符的ascii码在256范围内,貌似设置为130也是可以的。然后用key数组记录此字符上一次的位置。用cur表示以前一个字符为结尾的符合无重复的最大子串。

用字符当前位置与上次出现的位置为包含此位置字符的最大可能字串即i-key[i],如cur>i-key[i],则此字符已经在cur中出现过,则以此位置结尾的最大子串为i-key[i]. 否则cur中没有包含次字符,++cur为此位置最大子串。

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int key[256];
 5         int i,max=0,cur=0;
 6         for(i=0;i<256;i++)
 7           key[i]=-1;
 8         for(i=0;i<s.size();i++){
 9             if(key[s[i]]==-1) {
10                 cur++;
11                 key[s[i]]=i;
12             }
13             else {
14                 if (cur+1 >= i-key[s[i]])
15                    cur = i-key[s[i]];
16                 else
17                    cur++;
18                 key[s[i]]=i;
19             }
20             if(cur>max)
21              max = cur;
22         }
23         return max;
24     }
25 };

在leetcode上时间为16ms.

posted on 2016-07-22 15:38  aiheshan  阅读(121)  评论(0编辑  收藏  举报