Leetcode003. Longest Substring Without Repeating Characters
来源:互联网 发布:人工智能取代的职业 编辑:程序博客网 时间:2024/05/24 05:37
题目描述:
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.
题目大意:
求最长无重复字符子串
思路:
暴力算法:枚举子串再判是否有重复字符,时间复杂度O(n³),显然会TLE。
O(n)算法:记录每个字符上次出现的位置,具体见代码。
代码:
python:
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ pre = {} # 记录每个字符上次出现的位置 maxlen = 0 # 保存当前最长的长度 j = -1 # 当前字符串最远能向左延伸到哪里(若延伸太远则会遇到重复字符) for i in range(len(s)): c = s[i] if c in pre: # 若字符c已出现过 j = max(j, pre[c]) # 则最远只能延伸到c上一次出现的位置之后,否则出现两个c pre[c] = i # 更新c最后出现的位置 maxlen = max(maxlen, i - j) # 更新答案 return maxlen
c++:
class Solution {public: int lengthOfLongestSubstring(string s) { int pre[256], last = -1, maxx = 0; memset(pre, -1, sizeof(pre)); for (int i = 0; i < s.size(); i++) { last = max(last, pre[s[i]]); maxx = max(maxx, i - last); pre[s[i]] = i; } return maxx; }};
阅读全文
0 0
- leetcode003:Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters - leetcode003
- leetcode003 Longest Substring Without Repeating Characters
- Leetcode003-Longest Substring Without Repeating Characters
- LeetCode003 Longest Substring Without Repeating Characters
- Leetcode003. Longest Substring Without Repeating Characters
- Leetcode003 Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Python开发简单爬虫
- Spring的三种注入方式(Setter、构造函数和自动注入)
- js常用事件
- JS操作JSON总结
- 研究:Liferay研究(二)开发Liferay中几个常用的标签
- Leetcode003. Longest Substring Without Repeating Characters
- Java时间日期格式转换
- 随系统字体放大,某个View内容显示不全问题怎么修改?
- 改变=方法+坚持
- HTML中的实体字符
- Web.xml中Filter过滤器标签几个说明
- 如何编写带有超链接的TextView?
- Spring的两种注入方式的学习
- 最大值