双指针/滑动窗口/贪心 经典例题

文章讨论了多种编程问题,如字符串中不同整数计数、无重复字符子串、重复DNA序列检测、最小覆盖串、子数组长度、字符串排列、字符串调整以使相等和股票交易策略,都采用了双指针和滑动窗口技术来解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

双指针/滑动窗口

1805 字符串中不同整数的数目

class Solution {
public:
    int numDifferentIntegers(string word) {
        unordered_set<string> s;
        int n = word.size(), p1 = 0, p2;
        while (true) {
            while (p1 < n && !isdigit(word[p1])) {
                p1++;
            }
            if (p1 == n) {
                break;
            }
            p2 = p1;
            while (p2 < n && isdigit(word[p2])) {
                p2++;
            }
            while (p2 - p1 > 1 && word[p1] == '0') {
                p1++;
            }
            s.insert(word.substr(p1, p2 - p1));
            p1 = p2;
        }
        return s.size();

    }
};

vector<bool> occ;

for (int l = 0, r = 0 ; r < n ; r++) {
	//如果右指针的元素加入到窗口内后,根据题目判断进行滑动左指针
	while (l <= r && check()) l++;
}

3 无重复字符的最长子串

class Solution {
public:
    int lengthOfLongestSubstring(string s) {

        vector<bool> occ(128);
        int n = s.size();
        int res = 0;

        // 移动右指针
        for (int l = 0, r = 0; r <= n - 1; r++) {
            // 如果右边界的数字已出现过
            // 移动左边界,直至不出现
            while (occ[s[r]] && l <= r) {
                occ[s[l++]] = false;
            }
            occ[s[r]] = true;
            res = max(res, r - l + 1);
        }
        return res;
    }
};

187 重复的DNA序列

固定长度的滑窗

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        // 如果字符串长度小于10,直接返回空的vector
        if (s.length() < 10) {
            return vector<string>();
        }

        unordered_set<string> occ, res; // occ用于存储遍历过的子串,res用于存储重复的子串
        for (int i = 0; i <= s.length() - 10; ++i) {
            string subStr = s.substr(i, 10); // 截取长度为10的子串
            if (occ.find(subStr) != occ.end()) res.insert(subStr); // 如果子串已存在于occ中,则添加到res
            occ.insert(subStr); // 将当前子串添加到occ
        }
        return vector<string>(res.begin(), res.end()); // 将res中的子串添加到向量中并返回
    }
};

76 最小覆盖串*

class Solution {
private:
    vector<int> win = vector<int>(58, 0); // s 子串中不同字符的出现次数
    vector<int> tCnter = vector<int>(58, 0); // t 中字符的出现次数 A65 -- Z122

    bool check() {
        // 覆盖:win中每个字符的数量大于等于t的数量
        for (int i = 0; i < 58; i++) {
            if (tCnter[i] > win[i]) return false;
        }
        return true;
    }

public:
    string minWindow(string s, string t) {
        // 统计 t 中的字符出现次数
        for (char c : t) tCnter[c - 'A']++;
        // 把 s 转化为数组
        vector<char> cs(s.begin(), s.end());
        int minLen = 1000010, st = -1;

        // 滑窗模板
        for (int l = 0, r = 0; r < cs.size(); r++) {
            win[cs[r] - 'A']++;
            // 有可能更新
            while (l <= r && check()) {

                // 窗口大小复合规则
                if (r - l + 1 < minLen) {
                    minLen = r - l + 1;
                    st = l; // 记录起始位置
                }
                // 左指针右移动 l++
                win[cs[l++] - 'A']--;
            }
        }
        return st == -1 ? "" : s.substr(st, minLen);
    }
};

209 长度最小的子数组

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int res = 100010;

        for (int l = 0, r = 0, sum = 0; r < nums.size(); ++r) {
            sum += nums[r];
            // 有可能更新
            while (l <= r && target <= sum) {
                res = min(res, r - l + 1);
                sum -= nums[l--];
            }

        }
        return res == 100010 ? 0 : res;
    }
};

567 字符串排列

#include <string>
#include <vector>

class Solution {
private:
    std::vector<int> s1count = std::vector<int>(26, 0);
    std::vector<int> s2count = std::vector<int>(26, 0);

    bool check() {
        for (int i = 0; i < 26; ++i) {
            if (s1count[i] < s2count[i]) return false;
        }
        // 如果都是 >= ,代表已经覆盖
        return true;
    }

public:
    bool checkInclusion(std::string s1, std::string s2) {
        if (s1.length() > s2.length()) return false;

        // 统计该窗口下出现次数
        for (int i = 0; i < s1.length(); ++i) {
            s1count[s1[i] - 'a']++;
            s2count[s2[i] - 'a']++;
        }
        if (check()) return true;

        for (int l = 0, r = s1.length(); r < s2.length(); ++r, ++l) {
            s2count[s2[r] - 'a']++;
            s2count[s2[l] - 'a']--;
            if (check()) return true;
        }
        return false;
    }
};

1208 尽可能使得字符串相等

class Solution {
public:
    int equalSubstring(string s, string t, int maxCost) {
        int res = 0;
        for (int l = 0, r = 0, cost = 0; r < s.length(); ++r) {
            cost += abs(s[r] - t[r]);
            while (l <= r && cost > maxCost) {
                cost -= abs(s[l] - t[l]);
                l++;
            }
            res = max(res, r - l + 1);
        }
        return res;
    }
};

贪心

435 无重叠区间

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        # 优先选择结束的早的区间
        # 留下来可选的空间更大

        # 按照区间结束时间进行排序
        intervals.sort(key=lambda x: x[1])
        pre = intervals[0][1]
        cnt = 1

        for i in range(1, len(intervals)):
            # 如果当前区间的开始时间大于等于前一个区间的结束时间,不重叠
            if intervals[i][0] >= pre:
                cnt += 1
                pre = intervals[i][1]

        # 返回需要移除的区间数量
        return len(intervals) - cnt

455 分发饼干

class Solution:
    def findContentChildren(self, g, s):
        # 最小的饼干喂给最小的孩子

        # 对孩子和饼干进行排序
        g.sort()
        s.sort()

        cnt = 0
        i, j = 0, 0

        # 遍历饼干
        while i < len(s) and j < len(g):
            # 如果当前饼干满足当前孩子的胃口,那么直接喂给孩子
            # 孩子指针后移
            if s[i] >= g[j]:
                cnt += 1
                j += 1
            # 喂不饱则饼干指针后移
            i += 1

        # 返回满足的孩子数量
        return cnt

122 买卖股票的最佳时机

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int all = 0;
        // 今天买明天卖,可行就把获利加入
        for (int i = 1; i <= prices.size() - 1; ++i) {
            if (prices[i] > prices[i - 1]) {
                all += prices[i] - prices[i - 1];
            }
        }
        return all;
    }
};

### 哈希表数据结构例题与练习题 以下是关于哈希表的经典例题及其解析: #### 1. 最长回文串 (Easy) 给定一个字符串 `s`,找出其中最长的回文子序列长度。可以通过统计每种字符的数量并利用贪心策略解决此问题[^1]。 ```python from collections import Counter def longest_palindrome(s: str) -> int: count = Counter(s) length = 0 odd_found = False for char_count in count.values(): if char_count % 2 == 0: length += char_count else: length += char_count - 1 odd_found = True return length + 1 if odd_found else length ``` --- #### 2. 字母异位词分组 (Medium) 给定一组字符串,将所有的字母异位词分类成不同的组。可以使用哈希表记录每个排序后的字符串作为键,原始字符串列表作为值[^3]。 ```python from collections import defaultdict def group_anagrams(strs: list[str]) -> list[list[str]]: anagram_map = defaultdict(list) for s in strs: key = ''.join(sorted(s)) anagram_map[key].append(s) return list(anagram_map.values()) ``` --- #### 3. 无重复字符的最长子串 (Medium) 在一个字符串中找到不含任何重复字符的最长连续子串。滑动窗口配合哈希集合能够高效解决问题[^4]。 ```python def length_of_longest_substring(s: str) -> int: char_set = set() max_len = start = 0 for end, c in enumerate(s): while c in char_set: char_set.remove(s[start]) start += 1 char_set.add(c) max_len = max(max_len, end - start + 1) return max_len ``` --- #### 4. 最小窗口子串 (Hard) 在字符串 S 中找到包含 T 的所有字符的最小子串。双指针加哈希表可有效完成任务[^1]。 ```python from collections import Counter def min_window(s: str, t: str) -> str: need = Counter(t) window_counts = {} have, required = 0, len(need) l, r = 0, 0 min_len = float('inf') res = "" while r < len(s): c = s[r] window_counts[c] = window_counts.get(c, 0) + 1 if c in need and window_counts[c] == need[c]: have += 1 while have == required: if r - l + 1 < min_len: min_len = r - l + 1 res = s[l:r+1] d = s[l] window_counts[d] -= 1 if d in need and window_counts[d] < need[d]: have -= 1 l += 1 r += 1 return res ``` --- #### 5. C++ 实现:两数之和 (Easy) 给定整数数组 nums 和目标值 target,返回使它们相加为目标值的两个索引。C++ 可以借助 unordered_map 来快速定位所需元素的位置[^2]。 ```cpp #include <unordered_map> #include <vector> std::vector<int> twoSum(std::vector<int>& nums, int target) { std::unordered_map<int, int> map; for(int i = 0; i < nums.size(); ++i){ int complement = target - nums[i]; if(map.find(complement) != map.end()){ return {map[complement], i}; } map[nums[i]] = i; } return {}; } ``` --- ####
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值