博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode | Longest Substring Without Repeating Characters
阅读量:7010 次
发布时间:2019-06-28

本文共 1742 字,大约阅读时间需要 5 分钟。

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.

采用和类似的思路。这里用一个pos[256]来存储每个字符出现的位置。每次求以i为结束的最长长度。

如果当前字符出现过,那么长度就是上次出现pos[s[i]]到当前位置i的长度;

如果没出现过,那么长度++。

1 class Solution { 2 public: 3     int lengthOfLongestSubstring(string s) { 4         int pos[256]; 5         memset(pos, -1, 256 * sizeof(int)); 6         int len = 0, max = 0; 7         for (int i = 0; i < s.length(); ++i) { 8             if (pos[s[i]] >= 0) { 9                 for (int j = i - len; j < pos[s[i]]; ++j) pos[s[j]] = -1;10                 len = i - pos[s[i]];11             } else {12                 len++;13             }14             pos[s[i]] = i;15             if (len > max) max = len;16         }17         18         return max;19     }20 };

注意这里内循环(Line 9)中j是一直递增的,且这个范围是不会重复计算的。所以最坏情况下,内循环的总开销是O(n),整个算法最坏情况是O(2*n)。

第三次写,思路是统计到当前位置满足条件的串长度。每次找起始和终点。

1 class Solution { 2 public: 3     int lengthOfLongestSubstring(string s) { 4         if (s.empty()) return 0; 5         int start = 0, n = s.length(), next = 0, max = 1; 6         unordered_map
freqs; 7 8 while (start < n) { 9 for (; next < n && (freqs.count(s[next]) <= 0 || freqs[s[next]] == 0); next++) freqs[s[next]]++; 10 if (next - start > max) max = next - start;11 if (next == n) break;12 for (; start < next && s[start] != s[next]; start++) freqs[s[start]] = 0;13 freqs[s[start++]] = 0;14 }15 16 return max;17 }18 };

 

转载于:https://www.cnblogs.com/linyx/p/3730379.html

你可能感兴趣的文章
Mysql数据库调优和性能优化的21条最佳实践
查看>>
iOS视频播放-MPMoviePlayerController
查看>>
mysql导入导出数据中文乱码解决方法小结
查看>>
使用Mob短信sdk遇到的问题,解决
查看>>
android-------- 强引用、软引用、弱引用、虚引用使用
查看>>
HTML标签marquee实现滚动效果
查看>>
html字符操作
查看>>
oracle函数
查看>>
百度贴吧爬虫1.0
查看>>
ant+jmeter接口批量执行测试用例
查看>>
Mongodb
查看>>
小规模低性能低流量网站设计原则
查看>>
POI之PPT-元素操纵
查看>>
python 将txt文件转换成excel
查看>>
程序员N容N耻
查看>>
C语言基础及指针⑨联合体与枚举
查看>>
Discuz截取字符串
查看>>
连接数据库操作
查看>>
nginx错误:13: Permission denied
查看>>
如何检查一个单向链表上是否有环?
查看>>