leetcode 340 - 拥有k个唯一字符的最长子串 - Hard 双指针问题

题目: https://www.cnblogs.com/fatttcat/p/10302397.html
程序结构如下,
程序目录结构
CMakeLists.txt

cmake_minimum_required(VERSION 2.6)

project(longest_substr_with_at_most_k_distinct_chars)
set(CMAKE_CXX_STANDARD 20)
add_definitions(-g)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../../../include)
string(REPLACE ".cpp" "" file "main.cpp")
add_executable(${file}  "main.cpp")

main.cpp

#include "printer/printer.hpp"

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

using namespace std;

class Solution {
public:
    int lengthOfLongestSubstringKDistinct(string s, int k) {
        map<char, int> m;
        int left{0}, right{0}, cnt{0}, distance {0};
        // 滑动窗口右指针往右移, 遍历字符串
        while(right < s.size()) {
            char c = s[right];
            ++ m[c];
            // 首次出现
            // ++ cnt
            // cnt是用来统计k个不同的字符的
            if(m[c] == 1) {
                ++cnt; 
            } 
            // right 指针一直右移
            ++ right;
            // 说明已经有了k个字符了,开始移动左指针,直到 等于k个字符为止
            while(cnt > k) {
                auto tmp = s[left];
                // map中对应的值减少,减少到0时,表示减少了一个唯一字符,可以--cnt
                -- m[tmp];
                if(m[tmp] == 0) {
                    --cnt;
                }

                ++left;
            }

            distance = max(distance, right - left);
        }
        return distance;
    } 
};

void test_map() {
    map<char, int> m;
    ++m['a'];
    for(auto ele: m) {
        cout << "first: " << ele.first << " second: " << ele.second << "\n";
    }
}
auto main(int argc, char** argv) -> int {
    // test_map();
    Solution s;
    string str {"eceba"};
    int k {2};
    auto len_ = s.lengthOfLongestSubstringKDistinct(str, k);
    cout << "For string: " << str << "\n";
    cout << "Length of longest " << k << " distinct chars string is: " << len_ << "\n"; 
    return EXIT_SUCCESS;
}

程序输出如下,
程序输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值