leetcode 3

0(n*n)时间复杂度

注意ASCII的取值范围

只需要确定起始位置即可,暴力

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size()==0)return 0;
        int maxlength=0,length=0;
        int MapStr[500];
        for(int i=0;i<s.size();i++) {
            length=0;
            memset(MapStr,0,sizeof(MapStr));
            for(int j=i;j<s.size();j++) {
                if(MapStr[s[j]]==0) {
                    MapStr[s[j]]=1;
                    length++;
                }
                else break;
            }
            if(length>maxlength)
            maxlength=length;
        }
        return maxlength;
    }
};

0(n)

中间加了优化之间吧重复部分跳过相当于遍历两边

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         if(s.size()==0)return 0;
 5         int maxlength=0;
 6        int MapStr[300];
 7        int i=0,j=0;
 8        int length=s.size();
 9        memset(MapStr,0,sizeof(MapStr));
10        while(i<length) {
11            if(MapStr[s[i]]) {
12               maxlength=max(i-j,maxlength);
13               while(s[i]!=s[j]) {
14                   MapStr[s[j]]=0;
15                   j++;
16               }
17               i++;j++;
18            }
19            else {
20                MapStr[s[i]]=1;
21                i++;
22            }
23         }
24         maxlength=max(length-j,maxlength);
25         return maxlength;
26     }
27 };
原文地址:https://www.cnblogs.com/thefirstfeeling/p/5941349.html