LeetCode 热题 100之滑动窗口

37 阅读2分钟

3. 无重复字符的最长子串

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列, 不是子串。

提示:

  • 0 <= s.length <= 5 * 104
  • s 由英文字母、数字、符号和空格组成
class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int n = s.size();
        int res = 0;
        unordered_map<char, int> q;
        int j = 0;
        for(int i=0; i<n; i++){
            q[s[i]]++;
            while(j < n && q[s[i]] > 1){
                q[s[j]]--;
                j++;
            }
            res = max(res, i-j+1);
        }
        return res;
    }
};

438. 找到字符串中所有字母异位词

给定两个字符串 s 和 p,找到 s ****中所有 p ****的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。

示例 1:

输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

示例 2:

输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。

提示:

  • 1 <= s.length, p.length <= 3 * 104
  • s 和 p 仅包含小写字母
class Solution {
public:
    bool check(int a[26], int b[26]){
        for(int i=0; i<26; i++){
            if(a[i] != b[i]){
                return false;
            }
        }
        return true;
    }
    vector<int> findAnagrams(string s, string p) {
        int a[26], b[26];
        int m = p.size();
         int n = s.size();
        for(int i = 0; i<m ; i++){
            if(i < n){
                a[s[i]-'a']++;
            }
            b[p[i]-'a']++;
        }
        vector<int> res;
        if(check(a, b)){
            res.push_back(0);
        }
        for(int i=m; i<n; i++){
            a[s[i-m]-'a']--;
            a[s[i]-'a']++;
            if(check(a, b)){
                res.push_back(i-m+1);
            }
        }
        return res;
    }
};