C++
unordered_set无序容器使用方法: find(key)函数:查找以值为 key 的元素,如果找到,则返回一个指向该元素的正向迭代器;反之,则返回一个指向容器中最后一个元素之后位置的迭代器,即end()
class Solution {
public:
int lengthOfLongestSubstring(string s) {
if(s.size()<2) return s.size();
unordered_set<char> substr;
int maxsize = 0;
int left = 0;
for(int i = 0;i < s.size();i++)
{
while(substr.find(s[i]) != substr.end())
{
substr.erase(s[left]);
left++;
}
maxsize = max(maxsize, i+1-left);
substr.insert(s[i]);
}
return maxsize;
}
};
Python
set集合详细用法 Python的for循环只能是这么用for 元素 in 数组 如果像C++那样可以写成for i in range(n) 从1到n-1
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s)<2: return len(s)
substr = set()
maxsize, left, i = 0, 0 , 0
for char in s:
while char in substr:
substr.remove(s[left])
left += 1
i += 1
maxsize = max(maxsize, i-left)
substr.add(char)
return maxsize
|