题目描述:
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.
思路:
题目要求一个字符串中最长的没有重复字符的字符串长度,很明显可以用哈希表来实现,对出现的字符,哈希表中置1,两个指针一个指向头一个指向尾。并记录最长的没有重复字符的最长字符串的长度。
代码:
class Solution { public: int lengthOfLongestSubstring(string s) { int start = 0; int tail = 0; map<char,int> map_str; int max = 0; int count = 0; while(start<s.size()&&tail<s.size()){ if(map_str[s[tail]]==0){ map_str[s[tail]]++; count ++; tail++; if(max<count){ max = count; } }else{ map_str[s[start]]--; start++; count--; } } return max; } };