LeetCode - Longest Substring Without Repeating Characters
来源:互联网 发布:linux 调用中文输入法 编辑:程序博客网 时间:2024/06/08 07:56
题目描述:
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.
刚看到这道题时感觉无从下手,直接求解会很麻烦,而且复杂度会很高。比较简单而且易理解的方法是用一个数组pos[128],记录每个字符上次出现的位置,当遍历字符串发现某字符时,检查其上次出现的位置,若其出现在当前子字符串起点start前,说明当前子字符串中该字符串只出现一次,不需要更改起点;若其出现在当前子字符串起点start之后,说明当前子字符串中该字符出现两次,因此更改起点start=pos[s[i]]+1,得到新的无重复字符的子字符串。依次遍历字符串一遍就能产生所有满足条件的子字符串,然后每次都对子字符串长度进行判断,保留最大的字符串长度即可。需要注意的是,start初始值为0,那么要将pos[128]的所有元素初始值为-1,这样才能保证在最开始的时候所有字符上一次出现的位置在当前子字符串起点之前。
class Solution {public: int lengthOfLongestSubstring(string s) { int start=0; int maxLength=0; int pos[128]; for(int i=0;i<128;i++) { pos[i]=-1; } for(int i=0;i<s.size();i++) { if(pos[s[i]]>=start) { start=pos[s[i]]+1; } if(maxLength<(i-start+1)) { maxLength=i-start+1; } pos[s[i]]=i; } return maxLength; }};
- 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 23: Longest Substring Without Repeating Characters
- [LeetCode] 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] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- leetcode之Longest Substring Without Repeating Characters
- 按成绩蛇形分班算法
- 5.单件模式(Singleton Pattern)
- 剑指Offer:二叉搜索树的后序遍历序列
- Codeforces Round #239 (Div. 2) C Triangle(暴力)
- java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver问题解决
- LeetCode - Longest Substring Without Repeating Characters
- iptables中ULOG和NFLOG实现分析
- 一台电脑同时运行多个tomcat
- Oracle 使用scott用户登录提示密码过期
- Servlet之Filter过滤器
- 150. Evaluate Reverse Polish Notation
- Codeforces Round #239 (Div. 2) D Long Path(递推)
- malloc函数详解
- 安卓日记——用Retrofit写一个登录注册APP