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;
}
};
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;
}
};
相关文章推荐
- 2015多校第四场1003 hdu 5329 Question for the Leader
- 环境的问题真麻烦 message Unable to compile class for JSP:
- 新浪博客规则发布失败代码(分享)
- 常用的Eclipse快捷键
- 【C语言】杨氏矩阵C语言实现
- Shell Scripts - 条件语句,case语句,function功能
- Shell Scripts - 条件语句,case语句,function功能
- NEUQ 1088: Abbreviation
- C++ 类的静态成员详细讲解
- HDU 5355 Cake (WA后AC代码,详细解析,构造题)
- HTTP协议
- android anatomy and physiology 笔记
- iOS--为视图添加阴影
- flightsim
- iOS--为视图添加阴影
- [学习笔记]JavaScript基础--分享到
- HashMap与Hashtable的区别
- 【C语言】在字符串中找出第一个只出现一次的字符。 如输入“abaccdeff”,则输出'b'。
- 简易相册
- Opencv交叉编译到ARM(基于Qt)