您的位置:首页 > 其它

Longest Substring Without Repeating Characters —— Leetcode

2015-08-08 15:01 381 查看
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.

哈希表和滑动窗口解决重复字符的问题。

这题与其说是动态规划,不如说用滑动窗口来解决,维护begin、end和len三个变量来记录窗口的起始位置、终止位置和长度,维护一个256大小的hashtable来记录一个字符最近一次出现过的位置,具体代码如下:

class Solution {
public:
int lengthOfLongestSubstring(string s) {

vector<int> arr(256, -1);
int begin=0, len=0, longest=0;
for(int end=0; end<s.size(); end++) {
if(arr[s[end]] >= 0) {
begin = max(begin, arr[s[end]] + 1);
}
len = end - begin + 1;
longest = max(longest, len);

arr[s[end]] = end;
}
return longest;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: