LeetCode 3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
1,使用哈希表查目标子序列,暴力拆解,不快
int lengthOfLongestSubstring(char* s) { char table[128] = {NULL}; for(int i = 0;i < 128;i++) { table[i] = 0; } char *p = s; char *q = s; int MaxLength = 0; int TempLength = 0; if(p == NULL) { return MaxLength; } while(*p) { if(table[*p] == 1) { q++; p = q; TempLength = 0; for(int i = 0;i < 128;i++) { table[i] = 0; } } TempLength++; if(TempLength > MaxLength) { MaxLength = TempLength; } table[*p] = 1; p++; } return MaxLength; }
2,妙解抄录
用地址建表
int lengthOfLongestSubstring(char* s) { int len=0; char *end=s,*temp; char* addressTable[128]={NULL}; while(*end){ temp = addressTable[*end]; addressTable[*end]=end; if(temp>=s){ len=end-s>len?end-s:len; s = temp+1; }end++; } len=end-s>len?end-s:len; return len; }