Leetcode Longest Substring Without Repeating Characters
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.
题目的意思:输入一个字符串,求不含有重复字母的最长子串的长度
本题用哈希表的键值记录字母和字母的位置,为了记录长度,需要最长子串的开始位置。
每当扫描字符串的字符时,如果该字符已经出现过,而且现在的位置在开始位置之后,更新开始位置。
然后更新哈希表的值,并且保存最长子串的长度。
class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char,int> hash_map; int maxLen = 0,start = 0; for(int i = 0; i < s.length(); ++ i){ if(hash_map.find(s[i])!=hash_map.end() && hash_map[s[i]] >=start){ start = hash_map[s[i]]+1; } hash_map[s[i]] = i; maxLen = max(maxLen,i-start+1); } return maxLen; } };