标签:style io ar color sp for on art bs
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.
#include<stdio.h> #include<stdlib.h> #include<string.h> //时间复杂度为O(n^3),超时了 int llenthOfLongestSubstring(char *s) { int len=strlen(s); int i,j,k,flag; int sum=1,max=0; for(i=0;i<len;i++){ for(j=i+1,k=j;j<len;j++){ //printf("i-%d,j-%d\n",i,j); for(k=i,flag=1;k<j;k++){ if(s[j]!=s[k]) flag=1; else { flag=0; break; } } if(flag==1) sum++; else break; } if(sum>max) max=sum; sum=1; i=k; } return max; }
//时间复杂度为O(n),通过 int lenthOfLongestSubstring(char *s){ int len=strlen(s); int ht[256]; int i,curlen; int start=0,max=0; for(i=0;i<256;i++) ht[i]=-1; for(i=0;i<len;i++){ if(start>ht[s[i]]) ht[s[i]]=i; else{ curlen=i-start; if(curlen>max){ max=curlen; } start=ht[s[i]]+1; ht[s[i]]=i; } } curlen=i-start; if(curlen>max) max=curlen; if(max==0) return len; return max; } void main(){ printf("%d\n",lenthOfLongestSubstring("msboaguwnnyqxnzlgdgwpbtrwblnsadeuguumoqcdrubetokyxhoachwdvmxxrdryxlmndqtukwagmlejuu")); printf("%d\n",lenthOfLongestSubstring("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco")); printf("%d\n",lenthOfLongestSubstring("qopubjguxhxdipfzwswybgfylqvjzhar")); printf("%d\n",llenthOfLongestSubstring("qopubjguxhxdipfzwswybgfylqvjzhar")); }
Longest Substring Without Repeating Characters
标签:style io ar color sp for on art bs
原文地址:http://blog.csdn.net/uj_mosquito/article/details/41871951