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

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.

思路:依次遍历字符串,若当前字符未出现过,则将其加入当前子串;若其在当前子串中出现过,则去掉当前子串该位置及其之前的所有字符。

 1 class Solution { 2 public: 3     int lengthOfLongestSubstring( string s ) { 4         int ret = 0, prev = -1, slen = s.length(); 5         for( int i = 0; i < slen; ++i ) { 6             int k = i; 7             while( --k > prev && s[k] != s[i] ) { ; } 8             if( ret < i-k ) { ret = i-k; } 9             prev = k;10         }11         return ret;12     }13 };

 

Longest Substring Without Repeating Characters