首页 > 代码库 > LeetCode 3.Longest Substring Without Repeating Characters
LeetCode 3.Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, 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.
问题:求字符串不含重复字符的最长子字符串(注意子字符串是连续的,子序列可以不用连续,上面第三条例子)
思路:不含重复字符的最长子字符串,即为两个重复字符之间的子字符串中最长的一个(或者全部字符,整个字符串没有重复字符)。
代码如下:(参考九章算法http://www.jiuzhang.com/solutions/longest-substring-without-repeating-characters/)
1 class Solution { 2 public: 3 int lengthOfLongestSubstring(string s) { 4 // 题意为求不包含重复字符的最长子串 5 // left用以记录合法的最远左边界位置,last记录字符上一次出现的位置 6 int ans = 0, left = 0, len = s.length(); 7 int last[255]; 8 memset(last, -1, sizeof last); 9 10 for (int i = 0; i < len; i++) {11 // 上次出现位置在当前记录边界之后,即该子串中出现了重复字符,需调整left使得子串合法12 if (last[s[i]] >= left) left = last[s[i]] + 1;13 last[s[i]] = i;14 ans = max(ans, i - left + 1);15 }16 return ans;17 }18 };
LeetCode 3.Longest Substring Without Repeating Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。