1.题目描述
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
2.示例
示例 1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
题目链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
2.题目分析
本题可以利用“滑动窗口”的方法来解决,如果从索引i到j-1之间的子字符串sij已经被检查没有重复字符且记录此时子字符串长度,接下来再需要检查sj对应的字符是否已经存在于子字符串sij中。若存在则为重复子序列,则从子序列删除此字符及此字符前的字符;若不存在,则不重复字符串长度增加1,并将此字符添加到此子字符串中,作为当前子字符串,继续往后遍历检查。
3.题目解答
#include<iostream>
#include<string>
#include<set>
#include<algorithm>
using namespace std;
int lengthOfLongestSubstring(string s) {
int i = 0, j = 0;
int res = 0;
set<char>subS;
int n = s.size();
set<char>::iterator it;
while (i<n && j<n) {
if ((it = subS.find(s[j])) != subS.end()) {
subS.erase(s[i++]);
}
else {
subS.insert(s[j++]);
res = max(res, j - i);
}
}
return res;
}
int main() {
string s;
cin >> s;
cout << "result = " << lengthOfLongestSubstring(s) << endl;
system("pause");
return 0;
}