字符串的最长不重复字串

(start,i)表示当前发现的最大长度不重复字串,当遍历到i+1时候,看a[i+1]是不是在(start,i)里面(用map),有两种情况

    其中map<char,idex> 记录每个字符出现的位置。

    1)如果在map里且当前遍历索引>start,那么计算目前最大长度MAX=max(i-start,MAX),并且更新start=m[c]+1;

    2) 否则,那么更新最大长度+1。

int longestSubstring(string A, int n) {
     map<char, int> m; //表示字符串中每个字符是否出现,初始化为0,表示未出现  
     int start = 0,MAX = 0;  
     //遍历该字符串,每遍历一个字母时,利用map去找该字母最近一次出现是什么时候  
     //中间这一段便是无重复字符的字符串。  
     for (int i = 0; i <= n; i++){  
         char c = A[i];    
         if (m.find(c)!=m.end() && m[c] > start){    
             start = m[c] + 1;  
             MAX=max(i-start,MAX);
         }
         else{
             MAX = max(MAX, i - start + 1); 
         }
         m[c] = i;   //map添加数据  mapStudent[char] = int 
     }    
     return MAX;
}

 

猜你喜欢

转载自blog.csdn.net/asdasdasdasasd1111/article/details/81015946