Leetcode 3. Longest Substring Without Repeating Characters
来源:互联网 发布:淘宝开朗爸的店怎么样 编辑:程序博客网 时间:2024/05/22 05:51
题目:3. Longest Substring Without Repeating Characters
要求:
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.
Subscribe to see which companies asked this question.
思路:
首先解释每个数据的意义:
ans为最终的结果,left表示我们最终子串最左边的字母在string s中的位置
last数组表示所检测的字母的上一次出现时在string s中的位置
然后思路就很清晰了
先对last数组赋值,全部置为-1,表示之前都没出现过
然后进行遍历
如果:该字母上一次出现时在left的后面(last[s[i]] >= left),表示该字母已经出现过了,重复了
那么:left就赋值为这个字母上一次出现的位置的下一位
否则:表示该字母就是第一次出现,left不用动,但是这个字母在string s 中就有位置了,得赋值,也就是i
最后:比较ans 和 i - left + 1的大小
然后return 就好
代码:
class Solution {public: int lengthOfLongestSubstring(string s) { int ans = 0; int left = 0; int last[255]; memset(last, -1, sizeof last); for (int i = 0; i < s.length(); i++) { if (last[s[i]] >= left) { left = last[s[i]] + 1; } last[s[i]] = i; ans = max(ans, i - left + 1); } return ans; }};
- [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
- 初窥 react-native
- springboot学习总结
- Android中Canvas绘图之PorterDuffXfermode使用及工作原理详解
- PAT 乙级 1048. 数字加密(20) Java版
- spring AOP
- Leetcode 3. Longest Substring Without Repeating Characters
- 纯Java实现网易邮箱发送邮件
- 【SSLGZ 1040】合并果子
- struct 复习
- 开启记录
- SQL四种语言:DDL,DML,DCL,TCL
- 易企秀12.4 模板编辑无法删除页面问题分析
- Linux之软件包管理
- 关于vue的一些自我心得