【Leet Code】Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters

 Total Accepted: 20506 Total Submissions: 92223My 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>
哈哈,厲害厲害!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章