无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
滑动窗口解法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char, int> dic; int i = -1, res = 0, len = s.size(); for(int j = 0; j < len; j++) { if (dic.find(s[j]) != dic.end()) i = max(i, dic.find(s[j])->second); dic[s[j]] = j; res = max(res, j - i); } return res; } };
|
动态规划解法:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char, int> dic; int res = 0, tmp = 0, len = s.size(), i; for(int j = 0; j < len; j++) { if (dic.find(s[j]) == dic.end()) i = - 1; else i = dic.find(s[j])->second; dic[s[j]] = j; tmp = tmp < j - i ? tmp + 1 : j - i; res = max(res, tmp); } return res; } };
|
标题2
正文