LeetCode--Longest Substring Without Repeating Characters

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36124194/article/details/82586610

#Longest Substring Without Repeating Characters
###题目
Given a string, find the length of the longest substring without repeating characters.
####Example

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", which the length is 3.

####Example

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

####Example

Input: "pwwkew"
Output: 3
Explanation: 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.

###分析
这题如果用c++来实现的话应该是很容易的,因为c++本身就存在substring之类的库可以调用,但用c来实现需要一点技巧,如果按照普通的遍历,会有时间的限制,我们仔细观察可以得出以下特征:

  1. 当字符与前面的某个字符重复的时候,这是个重新遍历的临界点,这时选择的遍历起点是重复字符的前面一个的下标,这样可以减少遍历次数。
    ###源码
int lengthOfLongestSubstring(char* s) {
    int len = strlen(s);
    int *count = (int*)malloc(256*sizeof(int));
    memset(count,0,256*sizeof(int));
    int *last_seen =  (int*)malloc(256*sizeof(int));
    memset(last_seen,0,256*sizeof(int));
    int max = 0;
    int tag = 0;
    for(int i = 0; i < len; i++) {
    	count[s[i]]++;
    	if(count[s[i]] > 1) {
    		if(max < tag) {
    			max = tag;
    		}
    		tag = 0;
    		memset(count,0,256*sizeof(int));
    		i = last_seen[s[i]];
    		memset(last_seen,0,256*sizeof(int));
    		continue;
    	} else {
    		tag++;
    		last_seen[s[i]] = i;
    		if(max < tag) {
    			max = tag;
    		}
    	}
    }
    free(count);
    free(last_seen);
    return max;
}

猜你喜欢

转载自blog.csdn.net/qq_36124194/article/details/82586610