首页 > 代码库 > 【Leet Code】Longest Substring Without Repeating Characters
【Leet Code】Longest Substring Without Repeating Characters
Longest Substring Without Repeating Characters
Total Accepted: 20506 Total Submissions: 92223My SubmissionsGiven 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。