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.
思路:遍历字符串找最长不重复字串,用hash表记录下已有的字符,用begin来记录开始计数的位置。如果下一个字符在hash表中已经记录了,就修改begin和hash的值来继续下一次查找
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 int maxLength=0;//记录下最长的不重复字串的长度 5 int length=0; 6 int begin=0;//记录下开始计算长度的位置 7 short hash[128];//哈希表,ASCII码,最多不超过128个字符 8 memset(hash, 0, sizeof(hash)); 9 for(int idx=0; idx<s.size(); ++idx) 10 { 11 12 int key=s[idx]-‘\0‘; 13 if(hash[key]==0) 14 { 15 hash[key]=1; 16 ++length; 17 if(length>maxLength)maxLength=length; 18 if(maxLength==128)return 128;//如果最大长度达到128,立即返回,无须再比较下去 19 }else{ 20 while(s[begin]!=s[idx]) 21 { 22 int key=s[begin]-‘\0‘; 23 hash[key]=0; 24 --length; 25 ++begin; 26 } 27 ++begin; 28 } 29 } 30 return maxLength; 31 } 32 };