当前位置:网站首页>力扣 无重复字符的最长子串 C语言 题解
力扣 无重复字符的最长子串 C语言 题解
2022-06-10 00:06:00 【6映辰】
**
无重复字符的最长子串
**
一、完整题目
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串的长度。
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。请注意,你的答案必须是子串的长度,“pwke” 是一个子序列,不是子串。
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
二、解题思路
采用哈希表以及滑动窗口的思想:
- 开辟一个127空间的数组 Hash[127] ,用来存储位置,初始化都为 0
- 定义一个左指针,定义一个右指针,初始化时,都指向字符串的开头
- 定义一个变量用来存储最大长度
- 进行循环,只要右指针指向的的不为空就继续循环,每次循环右指针向前移动一位
- 每次循环时,进行判断:右指针指向的字符的哈希表不为 0 (表明之前已出现过) , 并且左指针 在上次此字符出现位置的左侧。将左指针重新指向此字符现在出现的位置。
- 记录此轮出现字符的位置
- 并计算此时的不重复字符串长度,并于上轮进行比较,记录下大的的值
- 进行新一轮的循环,直至字符串遍历完成

三、编写代码
int lengthOfLongestSubstring(char * s){
//Hash
int hash[127] = {
0};
//双指针
int left = 0;
int right = 0;
int max = 0;//存储最大长度
//循环遍历数组
while (s[right])
{
if (hash[s[right]] && left < hash[s[right]])//右侧有重复
{
left = hash[s[right]];//左侧向前移动
}
hash[s[right]] = right + 1;
max = max < (right - left + 1) ? (right - left + 1) : max;
right++;
}
return max;
}
四、测评结果
五、总结评价
这是一道特别经典的题目,大家一定好好练习,主要学习思路,自己敲代码,敲不出来,再来看我的代码,主要掌握哈希表的用法,以及滑动窗口的思想 (我记得第一次接触这个概念是在计算机网络的书上将的,TCP 协议利用这个思想进行传输的)。
我之后会主要更新力扣的专题,希望大家一样跟我每天刷力扣
有问题欢迎各位大佬指出
力扣系列将持续更新,欢迎关注,一起学习
边栏推荐
猜你喜欢

Do your filial duty to make an old people's fall prevention alarm system for your family

Basic and introductory knowledge for PHP learning

pycharm 2022永久激活版下载,亲测有效

谁说Redis不能存大key

Sarsa

Q-learning

wps合并单元格快捷键是什么

DDD driven domain design learning notes

Aquanee will land in gate and bitmart in the near future, providing a good opportunity for low-level layout

Opencv architecture
随机推荐
低边驱动和高边驱动
你了解单例模式吗?反正我不了解。
Go zero micro Service Practice Series (II. Service splitting)
BP neural network inversion of water quality parameters based on MATLAB
Illustration Google V8 06: prototype chain: how does V8 implement object inheritance?
Core [email protected] < 3.4 is no longer maintained and not recommended for usage due to the
Introduction to C # WPF layout control layoutcontrol
JS logic empty allocation double question mark syntax, double vertical bar syntax and optional chain syntax
Operator (day 2)
View the installable version number of the wheel on this computer
Retrofit2.0 添加Header的方法总结
MATLAB中对tif格式栅格影像读取-保存
Q-learning
If (obj! = null) is not required
Record a malicious keyword brushed by illegal drainage
10 common high-frequency business scenarios that trigger IO bottlenecks
How can C get entity class attribute names and values?
bias、variance介绍
ps标尺调精确位置在哪
IDC權威預測,中國制造業即將乘雲而上