当前位置:网站首页>力扣第三题——无重复字符的最长子串
力扣第三题——无重复字符的最长子串
2022-07-19 18:22:00 【InfoQ】
前言

题目分析

猛如虎的解法
public static int LengthOfLongestSubstring2(string? s)
{
if(string.IsNullOrEmpty(s))
{
return 0;
}
if(s.Length==1)
{
return 1;
}
char[] chars = s.ToCharArray();
Hashtable hashtable = new Hashtable();
int index = 0;
int maxLen = chars.Length;
List<int> list = new List<int>();
while (index < maxLen)
{
hashtable.Clear();
for (int i = index; i < chars.Length; i++)
{
if (hashtable.ContainsKey(chars[i]))
{
list.Add(hashtable.Count);
index++;
break;
}
hashtable.Add(chars[i], i);
if (i == chars.Length - 1)
{
index++;
list.Add(hashtable.Count);
}
}
}
list.Sort((x, y) => -x.CompareTo(y));
return list[0];
}
- 先排除掉特殊情况,空输入和单字符
- 常规字符,自然划分
- 在指定循环范围内(其实也是一步步缩短循环次数),利用hashtable的特性,把每个字节和索引值存入哈希表
- 每次循环都把哈希表的值计入到List里
- 循环结束后,整理List,按大小倒序排序,取第一个值就是题目要求的那个值。
标准的解法
public static int LengthOfLongestSubstring(string? s)
{
// 哈希集合,记录每个字符是否出现过
HashSet<Char> occ = new HashSet<Char>();
int n = string.IsNullOrEmpty(s) ? 0 : s.Length;
// 右指针,初始值为 -1,相当于我们在字符串的左边界的左侧,还没有开始移动
int rk = -1, ans = 0;
for (int i = 0; i < n; ++i)
{
if (i != 0)
{
// 左指针向右移动一格,移除一个字符
occ.Remove(s[i - 1]);
}
while (rk + 1 < n && !occ.Contains(s[rk + 1]))
{
// 不断地移动右指针
occ.Add(s[rk + 1]);
++rk;
}
// 第 i 到 rk 个字符是一个极长的无重复字符子串
ans = Math.Max(ans, rk - i + 1);
}
return ans;
}

边栏推荐
- 展锐市场副总裁周晨专访:回应了关于5G芯片春藤510的一切!
- 海上风电消防火灾报警系统中消防主机超远距离联网方案
- Basset: apprendre le Code réglementaire du génome accessible avec un réseau neuronal profond et cohérent
- 什么是虚拟DOM?如何实现一个虚拟DOM
- 论文领读|面向机器翻译的多语言预训练技术哪家强?最新进展一睹为快!
- TR069事件类型(EVENT CODE对应的含义)
- STL 笔记(六):容器——vector
- Who else can't answer the three MQ interview questions that an interviewer must ask??
- [software test] - water cup test case
- PyGame official document [translation] - pygame freetype
猜你喜欢
随机推荐
Step by step towards responsive programming (III) - common functional interfaces - function < T, R>
Use abp Zero builds a third-party login module (III): web side development
渲染优化:重绘(Repaint)和回流(Reflow)
Brain tumor segmentation using deep learning +HybridResUnet脑胶质瘤分割BraTs +论文解读
重装Win10系统怎么办?
性能优化:SPA单页应用首屏加载速度慢怎么解决?
网络爬虫DIY解决电商数据收集难题
STL 笔记(四):字符串
05 .FFmpeg 之 libavformat 库
KITS+肾脏肿瘤预处理+重采样+窗体变换+强度裁剪
搭建关键字驱动自动化测试框架
展锐首款5G基带芯片正式发布,成功跻身5G第一梯队!
校庆(暑假每日一题 2)
atof()、atoi()、atol()函数【详解】
STL 笔记(六):容器——vector
TCL展示多款折叠屏手机:屏幕、铰链均为自主研发!
What is the reason why the easycvr video Plaza device list cannot be scrolled and loaded?
What about reinstalling win10 system?
The difference between router and switch
Performance tools -- JMeter environment preparation