首页 > 代码库 > [LeetCode] Longest Substring Without Repeating Characters
[LeetCode] Longest Substring Without Repeating Characters
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.
以下用map记录关键信息,得到了O(n)的解法:
class Solution { public: int lengthOfLongestSubstring(string s) { if(s.size()<2) return s.size(); int lengthOfCurrent=1,maxLength = 1; //lengthOfCurrent表示当前字符往前具有的不重复字符个数。 map<char,int> m; //m里存放字符及字符在s中的下标。 m[s[0]]=0; for(int i = 1;i<s.size();i++) { if(m.count(s[i])==0 || m[s[i]]<i-lengthOfCurrent)//当前字符没与之前重复 或者 重复了但在前一个字符重复字符之前,对当前最大长度没有影响 lengthOfCurrent++; else lengthOfCurrent = i - m[s[i]]; m[s[i]] = i; if(lengthOfCurrent>maxLength) maxLength = lengthOfCurrent; } return maxLength; } };
[LeetCode] Longest Substring Without Repeating Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。