https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/

python

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        # 滑动窗口 [a, b] 确定当前窗口中无重复字符的长度
        # hash 表保存当前窗口字符及位置并匹配, max_num 记录当前最大值
        if s == '':
            return 0
        elif len(s) == 1:
            return 1

        hash = []
        a,b = 0,0
        max_num = 0
        hash.append(s[0])
        nums = len(s)
        while b < nums - 1:
            # 如果下一位字符不在hash表内,b+=1
            # 否则 a 跳转至hash中字符位置
            if s[b+1] in hash:
                tmp = hash.index(s[b+1])
                hash = hash[tmp + 1:]
                b += 1
                hash.append(s[b])
            else:
                hash.append(s[b+1])
                b += 1
            max_num = max_num if max_num>= len(hash) else len(hash)
        return max_num

s = Solution()
print(s.lengthOfLongestSubstring("pwwkew"))

cpp

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(!s.size()){
            return 0;
        }
        else if(s.size() == 1){
            return 1;
        }

        vector<char> hash = {};
        int a = 0, b = 0;
        int max_num = 0;
        hash.push_back(s[0]);
        int nums = s.size();
        while(b < nums - 1){
            auto it = find(hash.begin(), hash.end(), s[b+1]);
            if(it != hash.end()){
                int tmp = it - hash.begin();
                hash.erase(hash.begin(), hash.begin() + tmp + 1);
                b++;
                hash.push_back(s[b]);
            }
            else{
                hash.push_back(s[b+1]);
                b++;
            }
            max_num = max_num>=hash.size() ? max_num : hash.size();
        }
        return max_num;
    }
};

注意 find 是 #include 的函数,不是 std::vector 的成员函数;另外 vector.erase(vector.begin(), vector.end(), target) 可以相当于 python 的切片。