[leetcode] 3 Longest Substring Without Repeating Characters
来源:互联网 发布:打电话变声的软件 编辑:程序博客网 时间:2024/06/06 00:54
题目地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
题目描述: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.
我的代码:
class Solution {public: int lengthOfLongestSubstring(string s) { int n=s.size(); if(n<2)return n; int max=0; int start=-1; int a[200]; for(int i=0;i<200;i++)a[i]=-1; for(int i=0;i<n;i++){ if(a[s[i]]>start)start=a[s[i]]; a[s[i]]=i; if(i-start>max)max=i-start; } return max; }};
解题思路:
要求最长无重复连续子串,对于以位置i结束的子串而言,只需找到其前面最早出现重复的位置即可,利用动态规划,最早出现重复的位置有两种可能,一种是以i-1位置结束的最长字串里面有与i位置的字符相同的字符时,重复最早出现在该相同字符处,即前一个与i位置字符相同的字符处,另一种就是与i-1的重复位置相同。
因此,我们只需要两个变量,一个是前一个与i位置字符相同的字符的位置,这个可以用数组保存所有字符的最后出现位置,并同步更新,另一个就是i-1位置处的重复位置,就是我们需要的动态规划变量。
- 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 3LONGEST 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]3Longest 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
- mysql函数
- openstack project list
- 逐帧动画和补间动画的区别于各自的优缺点
- Linux下python升级至2.7步骤
- [笔记分享] [SCons] Qualcomm SCons之Flags
- [leetcode] 3 Longest Substring Without Repeating Characters
- Unity3D教你制作Bezier和Spine曲线编辑器二
- ubuntu解压命令全览(rar)
- Android四大组件及其联系纽带Intent
- Command line tools for Machine learning
- java学习7:银行存取款的例子,主要涉及对象同步问题,类似于数据库存取款,数据一致性问题
- bootstrap中好看的文件上传样式
- SurfaceView surface SurfaceHolder制作简单的相机
- mysql索引总结----mysql 索引类型以及创建