Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a _subsequence_ and not a substring.
C++ 解法一:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int res = 0, left = -1, n = s.size();
unordered_map<int, int> m;
for (int i = 0; i < n; ++i) {
if (m.count(s[i]) && m[s[i]] > left) {
left = m[s[i]];
}
m[s[i]] = i;
res = max(res, i - left);
}
return res;
}
};
本文探讨了如何在给定字符串中找到最长的无重复字符子串,通过三个实例展示了算法的应用,例如输入abcabcbb,输出为3,最长无重复子串为abc。文章提供了一种C++实现方案,利用哈希表跟踪字符位置,以O(n)的时间复杂度高效解决问题。
726

被折叠的 条评论
为什么被折叠?



