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>哈哈,厉害厉害!
【Leet Code】Longest Substring Without Repeating Characters
原文地址:http://blog.csdn.net/u012771236/article/details/38781385