题目:https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
题目描述
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.
方法:
先设立一个哈希,对于每个字符存入上次出现的位置,设立两个字符指针,两指针都在-1处,由右指针向向右扫描,每扫描一个,将该字符对应的哈希表中的值改为当前的位置,将该值与左指针位置比较,若该值大于左指针,将左指针赋值为该值,计算出两指针间 即字符串长度,判断该值是否为最大的字符串长度,即该串是否为最大字符。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> dict(256,-1);
int maxlen=0,start=-1;
for(int i = 0;i<s.length();i++){
if(dict[s[i]]>start){
start = dict[s[i]];
}
dict[s[i]] = i;
maxlen = max(maxlen,i-start);
}
return maxlen;
}
};