LeetCode OJ: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         if(!s.size()) return 0;
 5         int i = 0, j = 1;
 6         int maxSubLen = 1;
 7         bool canUse[256];   //char类型只有256个
 8         memset(canUse, true, sizeof(canUse));
 9         canUse[s[0]] = false;
10         while(j < s.size()){
11             if(!canUse[s[j]]){
12                 maxSubLen = max(maxSubLen, j - i);
13                 while(i < j){
14                     if(s[i] != s[j])
15                         canUse[s[i]] = true, ++i; 
16                     else{
17                         i++;
18                         break;
19                     }
20                 }
21             }else{
22                 maxSubLen = max(maxSubLen, j - i + 1);
23                 canUse[s[j]] = false;
24             }
25             ++j;
26         }
27         return maxSubLen;  
29     }
30 };

写的有点乱啊,见谅见谅。。

posted @ 2015-11-06 22:51  eversliver  阅读(399)  评论(0编辑  收藏  举报