LeetCode 3. Longest Substring Without Repeating Characters C++简洁代码

Given a string, find the length of the longest substring without repeating characters.
翻译:给出一个字符串,要求你找到没有重复字符的最长子串的长度。
Example 1:

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

Example 2:

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

Example 3:

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.

分析:

自己写的代码有4层循环…就不放出来了。
参考其他人的思路改良,最后时间复杂度降到O(n)。
不过这个搬过来的思路非常巧妙,可以说把hash table用到极致了。

AC代码

class Solution{
	public:
		int lengthOfLongestSubstring(string &str){
			int maxlen = 0,start = -1;
			vector<int > hash(256,-1);
			for(int i=0;i<str.size();i++)
			{
				start = max(start,hash[str[i]]);//start重置 
				hash[str[i]] = i;//赋值延后 
				maxlen = max(maxlen,i-start); 
			}
		return maxlen;
		}
};

后话:

“hash” is used to keep tracking the char in the input string you read every time. start indicates the position of starting position of the substring. At the beginning, it initializes all value in “hash” to -1. Then in the for loop, it scans every char in the string. If the char in the “hash”'s value is larger than “start”, it means it already in the substring. You should change the start position of substring to the repeat position and start a new count. “maxLen” records the maximum length of substring you have so far.

For example, the input is “aba”, you check hash[s[0]], which is hash[97] is -1. Therefore, you can change the hash[97] to 0. In this way, you keep recording the string char’s position in the dict. When you meet the second “a” in the input, hash[97] is 0 and larger than start, which is -1. Then you change start value to 0. When you apply length function ( i - start), you calculate the new substring length, which didn’t contain the substring before the first “a”.

Hope this can help explanation.

“hash”用于跟踪每次读取的输入字符串中的字符。start表示子串的起始位置。开始时,它将“hash”中的所有值初始化为-1。然后在for循环中,它扫描字符串中的每个字符。如果“hash”值中的字符大于“start”,则表示它已经在子字符串中。您应该将子字符串的开始位置更改为重复位置并开始新的计数。“maxLen“记录到目前为止的子字符串的最大长度。

例如,输入是“aba”,检查hash[s[0]],hash[97]是-1。因此,可以将散列[97]更改为0。这样,您就可以继续记录字符串字符在dict中的位置。当您在输入中遇到第二个“a”时,hash[97]是0,并且比start(即-1)大。然后将“开始”值更改为0。当应用长度函数(i-start)时,计算新的子字符串长度,它不包含第一个“a”之前的子字符串。

希望这能有助于解释。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值