0
点赞
收藏
分享

微信扫一扫

LeetCode-无重复字符的最长字串(c++,python)

Sophia的玲珑阁 2022-03-22 阅读 139

题目描述:

思路:

首先最直接的思路,就是从0开始遍历s,直到出现了与前面字符不一样的,记录这个时候的子序列长度,然后继续从1开始遍历,再记录,再从2开始.....一直到s.size()-1. 这样会超时,所以需要剪枝。

当我们找到了一个与前部分重复的,就去找这个重复的字符在哪里,找到的位置之前,可以砍掉很多已经知道不是最长子序列的索引了,就继续从找到的这个位置往后一位开始寻找,直到找完s。记录最长长度count

python我们可以利用dict和set 去做重复检测,c++可以用find函数。使用find函数要#include<algorithm>  

C++代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<char>t;//记录非重复元素
int count = 0;//最长的子序列的长度
int startindex = 0;//记录每一次寻找应从至少从哪开始 剪枝
int index = 0;//从0开始遍历s
while (1) {
if (index >= s.size()) break;
index = startindex;
while (index < s.size()) {
//int cnt = 0;//临时记录长度 其实可以之间用 t.size()返回
t.clear();
while (index < s.size()) {
//找不到就加入t
if (find(t.begin(), t.end(), s[index]) == t.end()) {
t.push_back(s[index]);
index++;
//cnt++;
}
else break;
}
if (t.size() > count) {
count = t.size();
if (index < s.size()) {
startindex = searchIndex(startindex, index, s[index], s) + 1;
}
break;
}
else {
if (index < s.size()) {
startindex = searchIndex(startindex, index, s[index], s) + 1;
}
break;
}
}
}
return count;
}
int searchIndex(int start,int end,char x,string s) {
for (int i = start; i < end; i++) {
if (s[i] == x) return i;
}
return end - 1;//虽然我们直到一定不会走这一条语句,但是不加 过不了编译
}
};

Python代码如下:

class Solution:
def searchIndex(self,start,end,x,s):
for i in range(end-start):
if s[i+start]==x:
return i+start
def lengthOfLongestSubstring(self, s: str) -> int:
t={}
count=0
startindex=0
index=0
while True:
if index>=len(s):
break
index=startindex
while index<len(s):
cnt=0
t={}
while index<len(s) and t.get(s[index],0)==0 :
t[s[index]] = 1
index += 1
cnt+=1
if cnt>count:
count=cnt
if index<len(s):
startindex=self.searchIndex(startindex,index,s[index],s)+1
break
else:
if index<len(s):
startindex=self.searchIndex(startindex,index,s[index],s)+1
break
return count
举报

相关推荐

0 条评论