[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;
}

  

posted @ 2014-10-01 09:19  supernigel  阅读(90)  评论(0编辑  收藏  举报