[LeetCode]Longest Substring Without Repeating Characters
来源:互联网 发布:重装系统提示网络电缆 编辑:程序博客网 时间:2024/06/02 05:15
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
[LeetCode Source]
思路:最早看到这题觉得对string遍历,然后对每一个位置寻找最长的无重复字母的节点,记录节点数,显然这样的解法是大于O(N)的,最差的情况是O(N^2)。
这个思路改进在于我们可以维护一个字串,每次遍历加一个字符,当有新的重复字母进来时,把之前含有重复字母的前面子串删除,这样我们就可以动态更新最大的字串。然后找出最大的长度。解法只需一遍遍历。
比如“efabcdaefghijk" 当第二个a进来时,删除第一个a的子串。变成”bcdaefghijk“。
代码如下:
class Solution {public: int lengthOfLongestSubstring(string s) { int ret = 0; size_t length = s.size(); if(length == 0) return 0; string rec; for(size_t i=0;i<length;++i){ if(rec.find(s[i])>=0){ rec.erase(rec.begin(),rec.begin()+rec.find(s[i])+1); } rec += s[i]; ret = rec.size()>ret?rec.size():ret; } return ret; }};
0 0
- 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
- jQuery定时器
- libpcap安装
- mybatis jdbcType: DATE & TIMESTAMP
- 医学图像处理开源软件包
- 欢迎使用CSDN-markdown编辑器
- [LeetCode]Longest Substring Without Repeating Characters
- 七牛上传的响应处理大全
- leetcode Interleaving String
- 判断*.xls文件单元格数据类型方法封装
- Libxml2库的编译和使用
- sublime text2编写html时如何快速地在指定浏览器中预览
- 配置minicom
- 有时候人活着就是累
- Android多媒体开发【10】-- android中OpenMax的实现【1】整体框架