1. 程式人生 > >leetcode第三題

leetcode第三題

採用動態規劃的方法去做,核心思想如下:

"滑動視窗" 

    比方說 abcabccc 當你右邊掃描到abca的時候你得把第一個a刪掉得到bca,

    然後"視窗"繼續向右滑動,每當加到一個新char的時候,左邊檢查有無重複的char,

    然後如果沒有重複的就正常新增,

    有重複的話就左邊扔掉一部分(從最左到重複char這段扔掉),在這個過程中記錄最大視窗長度

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int maxLength=0,count[128]={0},i,j;
        for(i=0,j=0;i<s.length();i++){
            if(count[s[i]]==1){
                maxLength=max(maxLength,i-j);
                while(s[i]!=s[j]){
                    count[s[j]]=0;
                    j++;
                }
                j++;
            }
            else count[s[i]]=1;
        }
     return max(maxLength,i-j);   
    }
};