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.
思路:
关键是记录当前子串的起始位置和用hash表记录每个字母出现的情况。
大神简约版的代码:
class Solution { public: int v[256]; //asciib码最多256个 int lengthOfLongestSubstring(string s) { memset(v,-1,sizeof(v)); //位置先全部赋值为-1 int start = 0, ans = 0; for (int i = 0; i < s.size(); ++i) { if (v[s[i]] >= start) { //如果当前子串中已经出现了该字符 更新答案和起始位置 ans = ans > i - start ? ans : i - start; start = v[s[i]] + 1; } v[s[i]] = i; } ans = ans > s.size() - start ? ans : s.size() - start; return ans; } };
思路是一样的,我自己好长好慢的代码:
int lengthOfLongestSubstring(string s) { unordered_map<char, int> v; int ans = 0; int len = 0; int start = 0; //记录当前子串的起始位置 for(int i = 0; i < s.size(); i++) { if(v.find(s[i]) == v.end()) { len++; v[s[i]] = i; } else { string tmp = s.substr(i - len, len); ans = (len > ans) ? len : ans; len = i - v[s[i]]; for(int j = start; j < v[s[i]]; j++) //把重复字符前面的字符次数都置0 { v.erase(s[j]); } start = v[s[i]] + 1; v[s[i]] = i; } } ans = (len > ans) ? len : ans; return ans; }
时间: 2024-12-29 11:41:05