问题描述:
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.
我的解题思路:
这个问题比较像之前写过的博客《【July程序员编程艺术】之最大字段和问题》,所以决定采用跟最大字段和一样的算法来解决这个问题:即使用hash表,在O(N)的时间内求解这个问题。
从最后一个字符开始,遍历整个字符串。每次循环都维护从当前字符开始的最长的子串的idx和实际长度,每新来一个字符,首先判断其是否出现于子串,如果没有则好办,直接将其与子串拼接。如果有,则需要修改相应子串的长度和idx,最后提交通过的程序如下:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char, int> hash_map;
int len = s.length();
if(len==0)
return 0;
int idx = len-1;
hash_map[s[len-1]]=idx;
int idx_max=len-1;
int tmp_max = 1;
int total_max=1;
if(len==1)
return 1;
for(int i=len-2;i>=0;i--) //substring start from i
{
char curr_st = s[i];
if(hash_map[curr_st]<=0)
{
hash_map[curr_st]=i;
tmp_max++;
if(tmp_max>total_max)
total_max=tmp_max;
}
else
{
if(idx_max>=hash_map[curr_st])
{
tmp_max=hash_map[curr_st]-i;
idx_max=hash_map[curr_st]-1;
hash_map[curr_st]=i;
if(tmp_max>total_max)
total_max=tmp_max;
}
else
{
hash_map[curr_st]=i;
tmp_max++;
if(tmp_max>total_max)
total_max=tmp_max;
}
}
}
return total_max;
}
};