1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Longest Substring Without Repeating Characters

Posted on 2013-10-09 13:57  1957  阅读(171)  评论(0编辑  收藏  举报

找一个串的最长的字母不重复的子串。

感觉和最小摘要差不多,两个指针搞搞就好。

start,end表示子串开始和结束位置

如果end放进去没有重复,那么end++

如果放入有重复,那么start++,一直到end放入没有重复。

然后就这样下去,找到最长的一个。

 

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (s == "") return 0;
        int start = 0;
        int end = start + 1;
        int len = s.length();
        bool charset[500] = {false};
        int ans = 1;
        charset[s[0]] = true; //记得要初始化啊!!!,就这个检查半天
        while(start < end && end < len){
            if(charset[s[end]] == false){
                //cout << s[end] << " " << charset[s[end]]<<endl;

                charset[s[end]] = true;
                end++;
                //cout << start << " " << end <<endl;
                if (end - start > ans) ans = end - start;
            }else{
                while(charset[s[end]] == true){
                    charset[s[start]] = false;
                    start++;
                }
                charset[s[end]] = true;
       
                end ++;
               if (end - start > ans) ans = end - start;
             
            }

        }
        
        return ans;
    }

};