[LeetCode]Longest Substring Without Repeating Characters

本文介绍了一个算法,用于解决在给定字符串中找到最长的无重复字符子串的问题。通过实例演示并提供代码实现,详细解释了如何通过遍历字符串并更新子串来找到目标子串。

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

解法1.

看一个例子:

S="abbdeca"。

t1="abbdeca",t1[1]==t1[2]。

t2="bbdeca",t2[0]==t2[1]。

t3="bdeca",一直扫描到最后。

t4="deca"、t5、t6、t7都同上。

我们在处理t1的时候已经扫描到了s[2],然后处理t3的时候扫描了s[2]到s[6],这两个子串已经扫描完了整个母串。

换言之,能使得子串停止扫描的位置只有两处:1.s[2];2.s[6](结尾)。

对于另一个例子S="aaab",能使子串停止扫描的位置分别是:s[1],s[2],s[3](结尾)。

 

所以我们可以考虑只扫描母串,直接从母串中取出最长的无重复子串。

对于s[i]:

1.s[i]没有在当前子串中出现过,那么子串的长度加1;

2.s[i]在当前子串中出现过,出现位置的下标为j,那么新子串的起始位置必须大于j,为了使新子串尽可能的长,所以起始位置选为j+1。

**注意字符范围,256即可,不能只定义27或者30,因为测试案例中不仅仅只有字母,还有其他符号!

// LongestSubstring.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class Solution {
public:
	int lengthOfLongestSubstring(string s) {
		int posArray[256];
		int max = 0;
		memset(posArray, -1, sizeof(posArray));
		int pa = -1;
		for (int i = 0; i < s.size(); i++)
		{
			if (posArray[s[i]]>pa)
			{
				pa = posArray[s[i]];
			}
			if (i - pa > max)
				max = i - pa;

			posArray[s[i]] = i;
		}
		return max;
	}
};
int _tmain(int argc, _TCHAR* argv[])
{
	string str = "bb";
	Solution ss;
	int max = ss.lengthOfLongestSubstring(str);
	cout << max << endl;
	system("pause");
	return 0;
}

  

转载于:https://www.cnblogs.com/supernigel/p/4003035.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值