LeetCode 3. Longest Substring Without Repeating Characters
来源:互联网 发布:数据库怎么删除表 编辑:程序博客网 时间:2024/06/03 16:37
Given a string, find the length of the longest substring without repeating characters.
题目描述
给定一个字符串,求出没有重复字母的最长连续子串长度
例如aab,最长为ab,长度为2
解题思路
0、cnt统计字符个数,st标记无重复字符的起点
1、建立一个散列表(初始化为-1),来记录每个字符上一次出现的位置
2、遍历字符串,若该字母所对应的散列表的值为-1,则该字母没在散列表中出现过,将其标记为对应的下标值
3、若该字母x在散列表中的值不为-1,则证明出现过。需要修改起点为(起点,x上次出现位置)的较大值
如:abcba,遍历到第二个b的时候,st为max(-1,1),等于1。当遍历到第二个a时候,st为max(1,0) = 1。
代码
class Solution {public: int lengthOfLongestSubstring(string s) { vector<int> vis(256, -1); int ans = 0; int cnt = 0; int st = 0; for (int i = 0; i < s.length(); i++) { if (vis[s[i]] == -1) { cnt++; vis[s[i]] = i; } else { st = max(vis[s[i]] + 1, st); vis[s[i]] = i; cnt = i - st + 1; } ans = max(cnt, ans); } return ans; }};至此:以O(n)的时间复杂度解决了求没有重复字母的最长连续子串长度。
如有更优秀解法,欢迎交流!
0 0
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- [leetcode] 3. Longest Substring Without Repeating Characters
- [Leetcode]3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- 【Leetcode】3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode - 3.Longest Substring Without Repeating Characters
- Leetcode 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters LeetCode
- (Leetcode)3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3. Longest Substring Without Repeating Characters
- 洗牌问题
- 综合界面
- YOLOv2训练自己的数据集(VOC格式)
- eclipse安装JAVA反编译插件
- 单片机之旅(串口)--1
- LeetCode 3. Longest Substring Without Repeating Characters
- bzoj2134: 单选错位
- invalidate、postInvalidat、 postInvalidateOnAnimation 区别
- ZJOI2017 游记
- PAT1014 福尔摩斯的约会
- idea 的pom文件添加 dependency 无法更新
- Alignment trap
- 基础指南:利用Sed Stream编辑器在Linux中处理文本
- c++ 调用java等方法关键点