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);   
    }
};

猜你喜欢

转载自blog.csdn.net/hua111hua/article/details/83042838