3.Longest Substring Without Repeating Characters

来源:互联网 发布:网站源码腾讯 编辑:程序博客网 时间:2024/05/09 02:17

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.

class Solution {public:    int lengthOfLongestSubstring(string s) {       unordered_map<char, int> myMap;   string::iterator iter = s.begin();   int pre = 0;   int next = 0;   int index = 0;   int maxLength = 0;      for (; iter != s.end(); ++iter,index++)   {   if ( myMap.find(*iter) == myMap.end() )   {   next = index;   myMap[*iter] = index;   if (maxLength < next - pre + 1)   maxLength = next - pre + 1;   }   else   {           if (myMap[*iter] < pre)  {  next = index;  if (maxLength < next - pre + 1)     maxLength = next - pre + 1;  myMap[*iter] = index;  }    else   {  next = index;  if (maxLength < next - pre)     maxLength = next - pre;  pre = myMap[*iter] + 1;  myMap[*iter] = index;  }      }   }         return maxLength;    }};


0 0
原创粉丝点击