LeetCode 3. Longest Substring Without Repeating Characters (C++/python)
来源:互联网 发布:美国白银数据公布 编辑:程序博客网 时间:2024/04/28 18:49
第二次
C++:
class Solution {public: int lengthOfLongestSubstring(string s) {int length = 0;string subs;for (char c: s) {if (subs.find(c) == string::npos) {subs += c;length = max(length, int(subs.size()));} elsesubs = subs.substr(subs.find(c)+1) + c;}return length;}};python:
class Solution(object):def lengthOfLongestSubstring(self, s):substr = ''length = 0i = 0for i in range(0, len(s)):if substr.find(s[i]) == -1:substr = substr + s[i]length = max(length, len(substr))else:substr = substr[substr.find(s[i])+1:] + s[i]return length
第一次
dp[i]代表自下标j (j<=i)起,到i的Longest Substring Without Repeating Characters.
已知dp[i-1], 则从i-1开始,往前遍历至i-dp[i-1], 看是否有重复的元素(下标为j);
若有,dp[i] = i-j;
反之,dp[i] = dp[i-1] + 1;
for (int j = i-1; j>=i-dp[i-1]; -- j){if (s[i] == s[j]){dp[i] = i-j;break;}}// dp[i]初始化为0, 此时仍为0则表示未发现其与之前的[i-dp[i-1], i-1]这条子串中有相同的元素,即if没被执行dp[i] = dp[i]==0? dp[i-1]+1: dp[i];
代码:
class Solution {public: int lengthOfLongestSubstring(string s) {if (s.size()==0){return 0;}vector<int> dp(s.size(), 0);int max=1;dp[0] = 1;for (int i = 1; i < s.size(); ++ i){for (int j = i-1; j>=i-dp[i-1]; -- j){if (s[i] == s[j]){dp[i] = i-j;break;}}dp[i] = dp[i]==0? dp[i-1]+1: dp[i];max = dp[i]>max? dp[i]: max;}return max; }};
0 0
- LeetCode 3. Longest Substring Without Repeating Characters (C++/python)
- 【leetcode】3. Longest Substring Without Repeating Characters(Python & C++)
- Leetcode -- Python -- Longest Substring Without Repeating Characters
- 【Leetcode】【python】Longest Substring Without Repeating Characters
- [LeetCode]3 Longest Substring Without Repeating Characters (C++,Python实现)
- 3.Longest Substring Without Repeating Characters Leetcode Python
- [Leetcode]3. Longest Substring Without Repeating Characters @python
- Leetcode题解(Python): 3.Longest Substring Without Repeating Characters
- [leetcode: Python]3. Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters题解python
- 【C语言】LeetCode 3. Longest Substring Without Repeating Characters
- LeetCode 3. Longest Substring Without Repeating Characters(C++)
- 【C++】【LeetCode】3. Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters c语言版
- LeetCode 3. Longest Substring Without Repeating Characters (C语言)
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- Swift学习笔记之变量,常量,字符串,数组
- Swift学习笔记之数据类型
- 【LeetCode】Merge k Sorted Lists
- 14种方法帮你养成终生的阅读习惯
- android 另外一个app
- LeetCode 3. Longest Substring Without Repeating Characters (C++/python)
- 大家社区 APP( http://www.dajiashequ.com )和四次元新浪微博的比较,以及阅读四次元新浪微博客户端的感想
- 第十四章 简单数据库应用的创建及MASTAPP介绍(十三)
- zoj 3790 离散化
- app优化思想
- zoj 3791 DP
- wget
- lightoj 1105 DP
- Codeforces Round #251 (Div. 2)