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= i-key[s[i]])15 cur = i-key[s[i]];16 else17 cur++;18 key[s[i]]=i;19 }20 if(cur>max)21 max = cur;22 }23 return max;24 }25 };
在leetcode上时间为16ms.