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.--------------------------------- thinking ------------------------------------------------------------------------------
At the very beginning, I've a wrong understanding of the question. I thought if there is a duplication, the whole substring will be abandoned. This is totally wrong. e.g. abcaef
Then after realizing this mistake, I still made mistakes on the codes at "when to reset the start value", which should be when the start is smaller than the index in hash table, but I wrongly say the index is bigger than 0. e.g. abba
https://leetcode.com/discuss/32350/my-9-lines-solution-in-c ----------------------------------- codes -----------------------------------------------------------------------------------
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.size();
if (len == 0) {
return 0;
}
//unordered_map<char, int> map;
int map[256];
memset(map, -1, sizeof(map));
int longest = 1;
int start = 0;
int i;
for (i = 0; i < len; i++){
//bug here, map[s[i]]should always larger than start, but not 0, because it might reverse the start far back. e.g. abba
if (map[s[i]] >= start) {
longest = max(longest, i - start);
start = map[s[i]] + 1;
//map.erase(s[i]);
}
map[s[i]] = i;
}
longest = max(longest, i - start);
return longest;
}
};
No comments:
Post a Comment