[LeetCode]Longest Substring Without Repeating Characters题解
来源:互联网 发布:期货分钟数据下载 编辑:程序博客网 时间:2024/06/16 08:24
Longest Substring Without Repeating Characters:
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.
刚刚看到这道题的时候还是比较难受的,因为左思右想也想不到解法。
O(n^2)算法复杂度的程序会超时,所以需要想出一种O(n)的方法得到最大子字符串。
看了一下LeetCode的discuss上,O(n)的方法基本思路都是一样的。
class Solution {public: int lengthOfLongestSubstring(string s) { //创建一个数组记录这个字符上一次出现的位置,初始化为-1 vector<int> charaterLastOccur(256 , -1); int len= 0, left = -1;//left是子字符串开始的位置 for(int i = 0; i < s.size(); i++){ //当前字符上一次出现的位置在left右边(>left)的时候,更新left的位置 if(charaterLastOccur[s[i]] > left){ left = charaterLastOccur[s[i]]; } //否则的话,更新res //新字符串长度(i-left)有可能比之前记录的len大,所以也更新一下 else{ len = max(len, i - left); } //一定记得在循环最后面加上这句,记录(更新)当前字符出线的位置 charaterLastOccur[s[i]] = i; } return len; }};
基本的思路都在注释里了,这里举个栗子巩固一下。
例如字符串“abcabcd“,当遍历完了前面的“abc”后,
1. 再遍历到“a”,因为a已经在left(=-1)后面出现过,所以left更新为a上次出现的位置0,此时从left后面到i就没有重复的字符啦(从left到i的字符串也是当前循环选定的符合条件的子字符串)
2. 再遍历到“b”,因为b已经在left(=0)后面出现过,所以left更新为b上次出线的位置1,
3. …
每次都有检查子字符串的长度并且把最大的保存下来,所以最后就得到了我们想要的无重复字符的最长子字符串的长度了。
- 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 题解(31): Longest Substring Without Repeating Characters
- LeetCode题解——3Longest Substring Without Repeating Characters
- [Leetcode题解]003 Longest Substring Without Repeating Characters
- LeetCode题解--3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters : LeetCode 题解
- Leetcode题解(Python): 3.Longest Substring Without Repeating Characters
- LeetCode题解:3. Longest Substring Without Repeating Characters
- leetcode 题解 3. Longest Substring Without Repeating Characters
- Leetcode题解:4. Longest Substring Without Repeating Characters
- Leetcode题解 - 3. Longest Substring Without Repeating Characters
- LeetCode题解-3-Longest Substring Without Repeating Characters
- LeetCode Algorithms 3. Longest Substring Without Repeating Characters 题解
- LeetCode题解 C++ Longest Substring Without Repeating Characters
- leetcode题解-3. Longest Substring Without Repeating Characters
- BZOJ 2006超级钢琴
- - Wireless Network POJ
- 【Recurrent Neural Network Regularization】读后感(未编辑完毕)
- Android日常积累--将某一项目作为Android Library(库文件)导入到另一项目中(添加项目依赖)
- SIFT算法知识和代码
- [LeetCode]Longest Substring Without Repeating Characters题解
- poj1006 模拟
- 简单的在Hadoop2.6.0上安装eclipse运行WORDCOUNT的总结笔记
- 面试题63. 二叉搜索树的第k个结点
- 这些iptables规则就够用了
- es6 class类
- 2-1、归一化
- 相机第三人称视角跟随
- 古文觀止卷九_箕子碑_柳宗元