您的位置:首页 > 其它

Longest Substring Without Repeating Characters

2015-06-01 09:20 127 查看
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.

开始拿到这道题的时候,开始没什么思路。后来在纸上画了一画,才发现了算法,其实也就用到了一个flag+哈希表。从左往右逐个字符遍历字符串,开始flag设置为-1。每遍历一个字符,若与左边已遍历过的字符没有冲突,则将当前字符的索引cur存入哈希表中。哈希函数f(key)=key,key为字符的ASCII码。若第一次发生冲突,则算出这次遍历得出的最长子串的长度(cur
- flag -1),与此前的len比较判断是否需要更新len,并在哈希表中将当前字符的索引cur覆盖前面这个字符的索引rep,再令flag = rep。但此时还要注意两种特殊情况:一种是遍历完全部字符串都没有发生冲突,则直接返回字符串的长度;第二种是若最后一个字符在当前这次遍历中(即flag置位后)没有发生冲突,则此次遍历得出的最长子串的长度为(cur - flag)。

Runtime:4ms

#define N 150
int searchHashTable(int * hashTable,char c)
{
int index = c;					//hash function
if( hashTable[index] >= 0 )
return hashTable[index];
else
return -1;
}
int lengthOfLongestSubstring(char* s) {
int len = 0,flag = -1,r = 0,strLen,cur;
strLen = strlen(s);
int hashTable
,rep;
for( cur = 0 ; cur < N ; cur++)
hashTable[cur] = -1;
for( cur = 0 ; cur < strLen ; cur++ )
{
rep = searchHashTable(hashTable,s[cur]);
if( rep == -1 || rep <= flag )
{
hashTable[ s[cur] ] = cur;	//fill in character's index of s string.
if( cur == strLen - 1 )		//boder situation:the last character does not collide.
{
len = len >= ( cur - flag ) ? len : ( cur - flag );
}
}
else
{
r = 1;
len = len >= ( cur - flag -1 ) ? len : ( cur - flag -1 );
hashTable[ s[cur] ] = cur;	//use the bigger index to cover the smaller one.
flag = rep;
}
}
if( r )
return len;
else					<span style="white-space:pre">	</span>//special situation:no collision occurs.
return strLen;
}




小结:

1.注意哈希表的使用:1)哈希函数;2)哈希表的大小,一定要能覆盖所有的f(key)值。

2.注意题目中的特殊情况与边界情况。

3.想不动时动动手,光动手不好好想也不行。学会抽象和归纳,用机器的角度思考问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode