您的位置:首页 > 其它

leetcode Longest Substring Without Repeating Characters解题记录

2017-02-12 21:08 537 查看
此题我的代码:

class Solution

{

public:
int lengthOfLongestSubstring(string s) 
{
unordered_map<char, int> record;
char pivot;
int max_lenth=0;
int head=0;
for (int i = 0; i < s.length(); ++i)
{
pivot = s[i];
if (record.find(pivot) != record.end())
{
max_lenth = max_lenth >= (i - head) ? max_lenth : (i - head);
i = record[pivot];
head = record[pivot] + 1;
record.clear();
}
else if (i != s.length()-1)
{
record[pivot] = i;
}
else
max_lenth = max_lenth >= (s.length() - head) ? max_lenth : (s.length() - head);
}
return max_lenth;
}

};

我的办法属于比较简单的遍历,一旦遇到有重复的字符串,则记录下当前的不重复字符串长度,并与当前最大不重复字符串长度比较,取最大值。

这个题目有一个O(n)的解法,用动态规划,其核心思想:

假设L(i) = s[m,i]是最大不重复字符串,

则找到s[i+1]:如果s[i+1]与L(i)中字符重复,找到重复字符k, m=max(k,m)

若s[i+1]不重复,则L(i) = s[m,i+1]

因为每个字符只需要遍历一次,故而为O(n)的复杂度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: