LeetCode算法题——Longest Substring Without Repeating Characters
来源:互联网 发布:bluehost域名跳转 编辑:程序博客网 时间:2024/06/01 07:33
题目概述
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.
分析
使用桶的思想,将每一个字符对应为一个桶。遍历字符串,桶中记录的的是每一个字符可能作为最长子字符串时的下标。置第一个字符对应的桶为起始下标,因为所有桶中原来的值都是-1,只有在遇到重复的字母的时候,才会导致桶中的值大于起始下标的情况,这时候只需要重新指定起始下标即可。同时以当前遍历的字符下标减去起始坐标就是当前最大子字符串的长度。
例如以字符串abcabcbb
为例,一开始起始下标为-1,dict[‘a’] = 0,dict[‘b’] = 1, dict[‘c’] = 2,在下标i = 3时,访问dict[‘a’]出现了桶值0 > -1大于下标的情况,这说明遇到了重复字母,因此需要对起始下标进行重新赋值,即当前的遍历下标3。按照此过程即可实现算法。
整个算法只遍历了一次数组,同时也并未调用较复杂的函数,时间复杂度为O(n),而空间复杂度更是仅为常量级O(1),精炼高效。
int lengthOfLongestSubstring(string s) { vector<int> dict(256, -1); int result = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; result = max(result, i - start); } return result;}
总结
· 在处理字符串,又涉及到非重复性的问题上,有时候可以利用桶的思想,因为字符的种类数目是有限的,只需要一个长度为256的数组既可以完成桶的构造。
· 起始下标变量可以形象地理解成为一个指针,这种思想在涉及遍历,研究顺序的题目中十分形象直观。
- LeetCode算法题——Longest Substring Without Repeating Characters
- 数据结构与算法[LeetCode]—Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters —leetcode第三题
- LeetCode算法题3:Longest Substring Without Repeating Characters
- leetcode算法题之 3. Longest Substring Without Repeating Characters
- LeetCode —— Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- [LeetCode]——Longest Substring Without Repeating Characters
- leetcode 003 —— Longest Substring Without Repeating Characters
- LeetCode——Longest Substring Without Repeating Characters
- LeetCode题解——3Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters —— Leetcode
- LeetCode——Longest Substring Without Repeating Characters
- #3 LeetCode——Longest Substring Without Repeating Characters
- [leetcode Q3] —— Longest Substring Without Repeating Characters
- leetcode——Longest Substring Without Repeating Characters
- leetcode——Longest Substring Without Repeating Characters
- 定义一个2维数组3行4列,求数组平均值最大值最小值js
- IDEA+Gradle+SpringBoot+SpringDataJPA+lambok(lombok有点问题)(一)
- 性能测试
- Linux系统调用原理
- 用props在外部子组件中使用父组件的数据
- LeetCode算法题——Longest Substring Without Repeating Characters
- Android获取视频某一帧图片
- VM虚拟机-物理机文件传输的设置方法
- Linux系统下Tomcat8启动速度很慢的解决方法
- Java学习第三天
- Mysql注入上传木马提权
- 读书笔记-05网站的高可用架构
- 地点
- 教程:使用树莓派连接Pixhawk飞控