LeetCode(3) Longest Substring Without Repeating Characters
源代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int num[256];
memset(num, 0, sizeof(num));
int start = 0, end = 0;
int len = s.length();
int ans = 0;
while (true) {
while (end < len && !num[s[end]]) {
num[s[end++]]++;
}
if (end - start > ans) {
ans = end - start;
}
if (end >= len) {
break;
}
while (num[s[end]]) {
num[s[start++]]--;
}
}
return ans;
}
};
- 该算法中,num[s[end]]处理,不是怎么明白
- 需要使用调试工具,看一下程序执行的过程
- num[s[end]],譬如第一次循环,s[0]=a,num[a]这里面的a是不是换算成了‘a’=97;所以num[s[end]]实际上num[97]
自己注释的代码如下
#include<string>
#include<cstring>
#include<iostream>
using namespace std;
/*
1.wsh
2.leetcode id=3
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int num[256];
memset(num, 0, sizeof(num));
int start = 0, end = 0;
int len = s.length();
int ans = 0;
while (true) {
while (end < len && !num[s[end]]) {
/*
1.s[end]='a' or 'b' or 'c' ...
2.num[s[end]],eg->num[a]=num[97],'a'->data
3.check character is repeated
*/
num[s[end++]]++;
}
if (end - start > ans) {
/*
1.判断最大子字符串
*/
ans = end - start;
}
if (end >= len) {
break;
}
while (num[s[end]]) {
/*
1.当有重复字符出现的时候,start+1,下一个字符为起始位置重新遍历
*/
num[s[start++]]--;
}
}
return ans;
}
};
int main(){
Solution s1;
string s("abcdabc");
cout<<s1.lengthOfLongestSubstring(s);
return 0;
}
- string 的用法也不是非常熟悉,查询了cplusplus.
- 字符串string s ,s[i]
class Solution {
public:
int lengthOfLongestSubstring(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int locs[256];//保存字符上一次出现的位置
memset(locs, -1, sizeof(locs));
int idx = -1, max = 0;//idx为当前子串的开始位置-1
for (int i = 0; i < s.size(); i++)
{
if (locs[s[i]] > idx)//如果当前字符出现过,那么当前子串的起始位置为这个字符上一次出现的位置+1
{
idx = locs[s[i]];
}
if (i - idx > max)
{
max = i - idx;
}
locs[s[i]] = i;
}
return max;
}
};
本文解析了LeetCode第3题“最长不含重复字符的子串”算法实现过程,通过C++代码详细解释了如何利用滑动窗口和字符计数数组来解决此问题,并提供了调试思路。
302

被折叠的 条评论
为什么被折叠?



