当前位置:网站首页>LeetCode0003——longest substring without repeating characters——Sliding Window
LeetCode0003——longest substring without repeating characters——Sliding Window
2022-07-22 10:29:00 【Zheyuan Zou】
今天在一个题库上看到了这道题,点进去一看很久之前竟然做过:
首先明确最长字串和最长子序列概念是不同的,前者必须要连续,后者只需要遵从源串的序列顺序即可。也正是因为字串必须连续,这就可以采纳滑动窗口算法来解决这个问题。
一般来说,滑动窗口算法其实就是用两个指针(索引值)圈定了一个线性序列的范围,然后大致按照此规律进行求解:
1.窗口上界持续向前推进
2.窗口下界同时检验着当前圈出来序列是否满足题目要求
3.如果不满足那么就修改窗口下界到下一个满足要求的位置
结束条件一般是窗口上界到达数组终点。
以下是此题的代码:
int lengthOfLongestSubstring(string s) {
if(s.size() == 0)
return 0;
/* Max is the maximum length of substring Behind is the lower bound of sliding window Ahead is the upper bound of sliding window */
int Max = 1;
int Behind = 0;
int Ahead = 1;
while(Ahead <= s.size() - 1)
{
/*test if the current sequence satisfies the request*/
for(int i = Behind ; i < Ahead ; ++i)
if(s[i] == s[Ahead])
/*if duplicated char is detected, jump to next position*/
Behind = i + 1;
/*modify the max length of substring if needed*/
if(Ahead - Behind + 1 > Max)
Max = Ahead - Behind + 1;
/*continue to increase the upper bound [Ahead]*/
++Ahead;
}
return Max;
}
边栏推荐
猜你喜欢
What are the definitions and principles of domain name hijacking and the solutions to domain name hijacking
json按格式逐行输出到文件
域名dns被劫持怎么办、dns被劫持怎么办、dns被劫持的解决方法
她力量系列八丨陈丹琦:我希望女生能够得到更多的机会,男生和女生之间的gap会逐渐不存在的
为什么memset不能将数组元素初始化为1?
如何将Word转化为Markdown文本
[reading notes] MySQL architecture and storage engine
进程的互斥、同步
Introduction to machine learning: support vector machine-6
linux安装oracle XE
随机推荐
Leetcode 21. merge two ordered linked lists
[summary of school recruitment] [review of old articles] Baidu internship gains meituan Netease Xiaomi Huawei vision offer
mysql查询blob
Comment le détournement de DNS peut - il être parfaitement réparé? Comment résoudre le problème du détournement de DNS
基于canny的亚像素的Devernay Algorithm
NC4 judge whether there is a ring in the linked list
What are the ways for Baidu homepage to be hijacked by TN? There are two ways to solve Baidu hijacking
Leetcode 300. longest increasing subsequence
dns被劫持有什么现象?DNS是什么 dns被劫持了如何解决
如何将Word转化为Markdown文本
什么是百度快照劫持?百度快照劫持原理和解决办法
Elastic Search 学习入门之核心概念(四)
Elastic Search 学习入门之Elastic Search的安装配置(一)
Spark资料查找
How to deal with DNS hijacked? Five ways to deal with it
Leetcode 32. longest valid bracket
Introduction to elastic search: search full text search (7)
[online case analysis] one-time slow query optimization and summary thinking
Core concepts of elastic search learning Introduction (4)
笔记:C语言