leetcode-无重复字符的最长子串

题目描述:

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

示例:

给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3。

给定 "bbbbb" ,最长的子串就是 "b" ,长度是1。

给定 "pwwkew" ,最长子串是 "wke" ,长度是3。请注意答案必须是一个子串,"pwke" 是 子序列 而不是子串

解题思路:

设立左指针a和右指针b,

b指针向右侧伸缩{

   对每个A[b]判断之前是否在之前的数组中出现过;

      如果出现过,指针a指向出现过位置的下一个位置;

更新右指针和最大长度;

}

代码:

#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
using namespace std;

class solution {
public:
	int lengthOfLongestSubstring(string s) {
		int start(0), end(0), length(0),result(0);
		int Ssize = int(s.size());
		while (end < Ssize) {
			char tempChar = s[end];
			
			for (int index = start; index < end; index++) {	
				//如果这个字符在数组中出现过,就让start 指向当前位置的下一位置,并更新长度
				if (tempChar == s[index]) {
					start = index + 1;
					length = end - start;
					break;
				}
			}
			end++;
			length++;
			result = max(result, length);
		}
		return result;
	}
};

int main() {
	string str = "abbbc";
	solution sol;
	int result = sol.lengthOfLongestSubstring(str);
	cout << result << endl;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值