【LeetCode】3. Longest Substring Without Repeating Characters
来源:互联网 发布:万能邮件群发软件 编辑:程序博客网 时间:2024/05/17 19: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 asubstring,"pwke"
is a subsequence and not a substring.
给定一个字符串,求不包含重复字符的最长子串(连续的字符)的长度。
解题思路:
要使得子串中不包含重复的字符,可以考虑将字符串从头扫到尾,用一个布尔数组记录当前子串使用的字符,这样可以避免每次生成一个子串后重新判断是否有重复字符。
使用布尔数组的时间复杂度为O(1);若使用STL的set,时间复杂度为O(log(n)).
使用一个队列记录子串的字符,每次读取字符串中的一个字符时,判断之前构成的子串是否包含这个字符。若包含,则将队列中的首字符弹出,相当于删掉当前的子串的前缀。最后将新字符加入子串中。
参考代码:
class Solution {public: int lengthOfLongestSubstring(string s) { bool vis[512]; memset(vis,0,sizeof(vis)); queue<char> q; int maxLen = 0; for (char c:s){ while(vis[c]){ char x = q.front(); q.pop(); vis[x] = false; } vis[c] = true; q.push(c); if (q.size() > maxLen)maxLen = q.size(); } return maxLen; }};
0 0
- [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]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 - 3.Longest Substring Without Repeating Characters
- Leetcode 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters LeetCode
- (Leetcode)3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3. Longest Substring Without Repeating Characters
- 恶意代码启动技术之释放资源文件
- C语言 获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列
- 工厂模式
- 全排列
- c++用引用实现俩个数的交换
- 【LeetCode】3. Longest Substring Without Repeating Characters
- Python基础知识
- 二元多项式
- ssh非交互式密码授权(一):expect自动输入密码、命令
- 微信小程序参考资料
- Memcache的原子性操作
- 离线环境下使用Maven打包Storm程序
- 如何理解超键、候选键、主键、外键的含义?
- varnish cdn 推送平台搭建