【Leet Code】Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

  Total Accepted: 20506  Total Submissions: 92223 My Submissions

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.


这题目有点儿坑啊,一开始没想明白,过一会儿才看懂题目要求,题目是找没有重复字符的最长子字符串,呵呵。也没想到什么好办法,只能while了:

class Solution 
{
public:
	int lengthOfLongestSubstring(string s) 
	{
		bool state[256];
		memset(state, false, sizeof(state));
		int ans = 0, l = 0, r = 0;
		while (r < s.length()) 
		{
			while (r < s.length() && state[ s[r] ] == false) 
			{
				state[ s[r++] ] = true;
			}
			ans = max(ans, r - l);
			while (l < r && s[l] != s[r])
			{
				state[s[l++]] = false;
			}
			l++, r++;
		}
	return ans;
	}
};
这个方法很明显了,用while里面嵌套while,可以说遍历的大部分字符串了。不过,有大神的代码如下:

class Solution 
{
public:
	int pos[256];
	int lengthOfLongestSubstring(string s)
	{
		// IMPORTANT: Please reset any member data you declared, as
		// the same Solution instance will be reused for each test case.
		for (int i = 0; i < 256; ++i)
			pos[i] = -1;
		int stp = -1, sz = s.size(), res = 0;
		for (int i = 0; i < sz; ++i)
		{
			if (pos[s[i]] >= stp)
			{  //update posistion
				stp = pos[s[i]] + 1;
			}
			pos[s[i]] = i;
			res = max(res, i - stp + 1);
		}
		return res;
	}
};//whose code is shorter than mine? Please notify me! I want to meet shorter codes!
大神就是大神,居然把找到的最近重复的字符的位置给记录下来了,佩服佩服,更让人为之疯狂的是,居然还在最后加上了:

<span style="font-size:18px;color:#ff0000;"><strong>whose code is shorter than mine? Please notify me! I want to meet shorter codes!</strong></span>
哈哈,厉害厉害!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值