LeetCode 3. Longest Substring Without Repeating Characters(线性处理, 哈希)
- By Scarb
- Scarb’s Blog
Tags:
- Hash Table
- Two Pointers
- String
问题描述
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
解题思路
- 先定义一个
dict
,用来存储所有字符最后出现的位置,初始化为-1. - 再设置
begin
变量,用以记录当前没有重复字符子串的起始位置,初始化为0。 max_len
为最大长度,初始为0.- 从左到右扫描字符串,读入每一位字符。当该位字符上一次出现的位置在
begin
之后,说明该字符重复。比较此时的字符串长度是否最长,如果是最长则赋给max_len
。 - 然后将
begin
移动到上一个重复字符的下标+1的位置(这样可以保证begin
到当前下标都没有重复),继续向后扫描。 - 最后返回
max_len
,此时还要将begin
到字符串末的长度再与max_len
对比,因为最后一次没有比。
- 从左到右扫描字符串,读入每一位字符。当该位字符上一次出现的位置在
参考代码
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256, -1); // ACSII_MAX = 256, means last pos of this repeating character
int max_len = 0; // longest substring len
int begin = 0; // begin index
for (int i = 0; i < s.size(); ++i)
{
if (dict[s[i]] >= begin)
{
max_len = max(i - begin, max_len);
begin = dict[s[i]] + 1;
}
dict[s[i]] = i;
}
return max((int)s.size() - begin, max_len);
}
};
int main()
{
string str = "abcabcbb";
auto sl = new Solution();
cout << sl->lengthOfLongestSubstring(str) << endl;
system("pause");
return 0;
}