题目:
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; map<char,int> mapping; 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; } };
时间: 2024-10-10 09:19:59