Leetcode——3. Longest Substring Without Repeating Characters
来源:互联网 发布:猫云seo 编辑:程序博客网 时间:2024/06/01 09:26
1. 概述
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.
这里使用到的方法是 滑动窗口算法(Slide Window Algorithm)求解,和 Minimum Size Subarray Sum 相似。
设下标 l 和 r, 把左开右闭 [l, r) 想象成一个窗口。
当 s[r] 和窗口内字符重复时, 则 l 向右滑动,缩小窗口。
当s[r] 和窗口内字符不重复时,则 r 向右滑动,扩大窗口,此时窗口内的字符串一个无重复子字符串。
在所有的无重复子字符串中,找到长度最大的,即为原问题解。
设下标 l 和 r, 把左开右闭 [l, r) 想象成一个窗口。
当 s[r] 和窗口内字符重复时, 则 l 向右滑动,缩小窗口。
当s[r] 和窗口内字符不重复时,则 r 向右滑动,扩大窗口,此时窗口内的字符串一个无重复子字符串。
在所有的无重复子字符串中,找到长度最大的,即为原问题解。
2. 编码
class Solution {public: int lengthOfLongestSubstring(string s) { if("" == s) return 0; //空串 if(1 == s.length()) return 1; //只有一个字符 if(2==s.length() && s.at(0)!=s.at(1)) return 2; int left(0), right(1), len(s.length()), max_len(1); unordered_set<int> setv; setv.insert(s.at(left)); while(right < len) { if(setv.count(s.at(right)) != 0) { setv.erase(s.at(left)); ++left; } //在集合中删除元素,直到没有与当前字符重复的时候 else { setv.insert(s.at(right)); ++right; max_len = max(max_len, (int)setv.size()); //记录最大的长度 } } return max_len; }};
阅读全文
0 0
- LeetCode——3. Longest Substring Without Repeating Characters
- Leetcode——3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters——LeetCode OJ
- 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
- Leetcode 3. Longest Substring Without Repeating Characters
- dvwa-sql injection(blind)
- Search for a Range
- 一个简单的用户登录接口
- ffmpeg简介
- 关于树莓派B+可用的Openwrt固件
- Leetcode——3. Longest Substring Without Repeating Characters
- android build 过程 (ramdisk.img、sytem.img、userdata.img)和 启动过程简单分析
- matlab实现一次性实现多个文件夹图片转化为.mat文件
- 无穷大量
- activity异常生命周期下的退出数据保存的方法
- Kotlin编程之嵌套类,内部类,匿名内部类
- 修改windows 7以后的无线网卡mac地址
- RecyclerView里嵌套带小圆点的无限轮播
- 查找细胞