算法课程Leetcode作业第二周技术博客
题目:3. Longest Substring Without Repeating Characters 难度:medium
题目描述
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.
分析
给定一个string,找出最长不重复的子String的长度,可以设定两个指针遍历String,每次遍历到下一次字符时检查是否之前出现过重复,我们可以用一个Set来存储已经出现过的字符,当新字符不在Set中时,记录当前长度并将该字符存储到Set中,当出现重复字符时,比较当前长度和历史最长长度,若当前长度大于历史最高,着将历史最高长度更改成当前长度,然后初始化Set和当前长度,将第二个指针移动一位从这里重新遍历,直到遍历完成。
代码
class Solution {
public:
int lengthOfLongestSubstring(string s) {
string::iterator it_1, it_2;
it_1 = s.begin();
it_2 = s.begin();
set<char> set_check;
int size_max = 0;
int size_pre = 0;
while(it_2 != s.end()) {
char temp = *it_2;
if (set_check.find(temp) != set_check.end()) {
if (size_pre > size_max) {
size_max = size_pre;
}
size_pre = 0;
set_check.clear();
it_1++;
it_2 = it_1;
} else {
set_check.insert(temp);
size_pre++;
it_2++;
}
}
if (size_pre > size_max) {
size_max = size_pre;
}
return size_max;
}
};
算法优化
第二个指针的移动其实可以不仅仅移动一位,而是移动到出现重复的字符的下一个字符开始
class Solution {
public:
int lengthOfLongestSubstring(string s) {
string::iterator it_1, it_2;
it_1 = s.begin();
it_2 = s.begin();
set<char> set_check;
set<char>::iterator set_it;
int size_max = 0;
int size_pre = 0;
while (it_2 != s.end()) {
char temp = *it_2;
if (set_check.find(temp) == set_check.end()) {
set_check.insert(temp);
size_pre++;
it_2++;
} else {
if (size_pre > size_max) {
size_max = size_pre;
}
while (*it_1 != temp) {
it_1++;
}
it_1++;
it_2 = it_1;
size_pre = 0;
set_check.clear();
}
}
if (size_pre > size_max) {
size_max = size_pre;
}
return size_max;
}
};
可以发现算法的运行时间略微减少,不过还是可以看出在分布上,离平均的运行时间相差挺大
leetcode官方答案
其实答案中未优化的部分和我的算法基本一致,就是用两个指针来遍历,但是官方的优化版本抛弃了使用Set来分辨一个字符的存在与否,而是定义了从字符到index的Map,这样就可以跳到我们要找的那个重复字符
用j来表示右边的那个指针位置,如果当前所指位置在Map中出现重复,着比较重复字符的index和i哪个大,将i更改为大的那个值
j - i + 1是当前长度,ans存储历史最长长度
算法将2n个步骤缩短为n个步骤,可以看出结果分析中运行时间减少的很明显