leetcode-3-字符串题-无重复字符的最长字串 发表于 2020-03-16 | 分类于 数据结构与算法 题目 解法12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455// 滑动窗口class Solution {public: int lengthOfLongestSubstring(string s) { int n = s.size(); if(s.empty()) return 0; if(n == 1) return 1; unordered_map<char, int> charIndex; int maxLen = 0; for(int i = 0, j = 0; j < n; ++j){ if(charIndex.count(s[j]) > 0){ i = max(i, charIndex[s[j]]); charIndex[s[j]] = j+1; }else{ charIndex.insert({s[j], j+1}); } maxLen = max(maxLen, j-i+1); } return maxLen; }};// 动态规划class Solution {public: int lengthOfLongestSubstring(string s) { int n = s.size(); if(s.empty()) return 0; if(n == 1) return 1; unordered_map<char, int> charIndex; int curLen = 0; int maxLen = 0; for(int i = 0; i < n; ++i){ if(charIndex.count(s[i]) > 0){ if(i - charIndex[s[i]] > curLen){ ++curLen; }else{ if(curLen > maxLen) maxLen = curLen; curLen = i - charIndex[s[i]]; } charIndex[s[i]] = i; }else{ ++curLen; charIndex.insert({s[i], i}); } } if(curLen > maxLen) maxLen = curLen; return maxLen; }};