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

题目描述:

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

提示:

  • 0 <= s.length <= 5 * 104
  • s 由英文字母、数字、符号和空格组成

思路:

首先最直接的思路,就是从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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值