给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其
长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b"
,所以其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是"wke"
,所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke"
是一个子序列,不是子串。
此问题网址在leecode中
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
解法1:
首先是直接暴力输出,两层循环(子字符串的左右),但是左边不动只往右边移动的时候,当出现新的字符与子字符串重合时,单纯的循环无法判别出新出现的字符与子字符串中间某个相同的情况
。对于此种问题,可以使用一个新的函数来判断新的字符是否已经子字符串出现,我的解决办法是使用set来直接判断
以下是我的代码
int lengthOfLongestSubstring(string s) { set<char>t; int left = 0, right = 0; int sum = 0; for (; left < s.size(); left++) { int change = t.size(); for (; right < s.size(); right++) { //t.insert(s[right]); if (t.find(s[right]) == t.end())//mei找到 { t.insert(s[right]); change++; if (sum < change) sum = change; } else { if (sum < change) sum = change; t.erase(s[left]);//将最左边删除 break; } } } return sum; }
优化解法2:思路是相似的
int lengthOfLongestSubstring(string s) { set<char>t; int res = 0, left = 0, right = 0; while (right < s.size()) { if (t.find(s[right]) == t.end())//没在里面 { t.insert(s[right++]); //res = max(res, t.size());//在c++中使用max会出现问题 if(res<t.size()) res=t.size(); } else { t.erase(s[left++]); } } return res; }
其余解法可参考:
https://www.cnblogs.com/ariel-dreamland/p/8668286.html
注:对于在v和leecode中使用max会显示错误:no matching function for call to 'max(int&, std::set<char>::size_type)'
其原因是VS把min和max这两个标识符定义成了宏
具体可转到此处:
http://www.cppblog.com/jince/archive/2010/09/14/126600.html