首页 > 代码库 > LeetCode Longest Substring Without Repeating Characters

LeetCode Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

解题思路:利用hashmap保存已经出现过的字母。

  1.如果这个字母没有出现过,则当前长度maxCurrent++,并将这个字母加入hashmap中。

  2.如果这个字母出现过,分2种情况,如果这个字母出现在计数器前面,则表明这个字母是无效的,maxCurrent++,并将当前字母放入hashmap中。如果这个字母出现在计数器之后,则表明是时候结算maxCurrent了,并更新计数器为hashmap[c]+1,maxCurrent更新为上个字母到现在的距离。

  3.重复直到字符串结束。

class Solution {public:      int lengthOfLongestSubstring(string s) {       int len = s.size();       int maxResult=0,maxCurrent=0,start=0;       unordered_map<char,int> hashMap;       for(int i=0;i<len;i++)       {           char c = s[i];           auto k = hashMap.find(c);           if(k==hashMap.end())           {               hashMap[c] = i;               maxCurrent++;           }           else           {               if(hashMap[c] < start)               {                   maxCurrent++;                   hashMap[c] = i;               }               else               {                   maxCurrent = i-hashMap[c];                   start = hashMap[c]+1;                   hashMap[c] = i;               }           }           maxResult = max(maxResult,maxCurrent);                  }       return maxResult;    }};

 

LeetCode Longest Substring Without Repeating Characters