1. 程式人生 > >【leetcode】3.Longest Substring Without Repeating Characters(c語言)

【leetcode】3.Longest Substring Without Repeating Characters(c語言)

Description:

Given a string, find the length of the longest substring without repeating characters.

Example1:

Input: “abcabcbb” Output: 3 Explanation: The answer is “abc”, with the length of 3.

Example2:

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

Example3:

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.

注意點: 1.空字串 2.視窗滑動方法

int lengthOfLongestSubstring(char* s) {
	if (s == "")	return 0;   //?????

	int max = 0,i=0,j=0,k,flag=0,max_tmp=0;

	while (s[j] != '\0')
	{	
		for (k = j-1; k >= i; k--)
		{
			if (s[k] == s[j])
			{
				flag = 1;
				break;
			}
		}   //有重複flag=1||迴圈滿了flag=0
		if (flag == 0) //迴圈滿了  更新當前最大值
max_tmp++; else //字元有重複,更新i值,視窗滑動,更新視窗長度 ;更新flag { i = k + 1; max_tmp = j - i + 1; flag = 0; } if (max_tmp > max) max = max_tmp; j++; } return max; }