题目:
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.
思路:
用一个map存放字符出现的position;用两个指针begin,end指向substr的首末;遇到相同字符时将begin移到该字符之前出现的后一位置,并更新该字符的position。
代码:C++ :
class Solution {public: int lengthOfLongestSubstring(string s) { if (s.length() <= 1) return s.length(); int begin = 0; int end = 0; mapmapping; int solve = 0; mapping[s[0]] = 0; while (end < s.length() - 1) { end++; if (mapping.find(s[end]) != mapping.end()) { int gap = end - begin; if (gap > solve) solve = gap; begin = mapping[s[end]] + 1 > begin ? mapping[s[end]] + 1 : begin; mapping[s[end]] = end; } else mapping[s[end]] = end; } int gap = end - begin + 1; if (gap > solve) solve = gap; return solve; }};
Reference :
本质上跟我的思路差不多,但是代码很简洁
int lengthOfLongestSubstring(string s) { vector 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; }
由此可知:
dict['A']与dict[65]等效,即与ASCII码对应