Leetcode3258. 统计满足 K 约束的子字符串数量 I

Every day a Leetcode

题目来源:3258. 统计满足 K 约束的子字符串数量 I

解法1:暴力

暴力枚举每一个子字符串,看是否满足 k 约束。

代码:

cpp 复制代码
/*
 * @lc app=leetcode.cn id=3258 lang=cpp
 *
 * [3258] 统计满足 K 约束的子字符串数量 I
 */

// @lc code=start
class Solution
{
public:
    int countKConstraintSubstrings(string s, int k)
    {
        int n = s.length();

        function<bool(string)> check = [&](string s) -> bool
        {
            int cnt0 = 0, cnt1 = 0;
            for (char &c : s)
            {
                if (c == '0')
                    cnt0++;
                else
                    cnt1++;
                if (cnt0 > k && cnt1 > k)
                    return false;
            }
            return true;
        };

        int cnt = 0;
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
            {
                string temp = s.substr(i, j - i + 1);
                if (check(temp))
                    cnt++;
            }
        return cnt;
    }
};
// @lc code=end

结果:

复杂度分析:

时间复杂度:O(n2),其中 n 是字符串 s 的长度。

空间复杂度:O(1)。

相关推荐
一个不知名程序员www3 小时前
算法学习入门 --- 哈希表和unordered_map、unordered_set(C++)
c++·算法
C++ 老炮儿的技术栈3 小时前
在C++ 程序中调用被 C编译器编译后的函数,为什么要加 extern “C”声明?
c语言·c++·windows·git·vscode·visual studio
%xiao Q3 小时前
GESP C++五级-202406
android·开发语言·c++
Sarvartha3 小时前
C++ STL 栈的便捷使用
c++·算法
夏鹏今天学习了吗4 小时前
【LeetCode热题100(92/100)】多数元素
算法·leetcode·职场和发展
Aevget4 小时前
MFC扩展库BCGControlBar Pro v37.2 - 全新的VS 2026可视化管理器
c++·mfc·bcg·界面控件·ui开发
C+-C资深大佬5 小时前
C++类型判断
开发语言·c++
Yu_Lijing5 小时前
基于C++的《Head First设计模式》笔记——模式合作
c++·笔记·设计模式
zmzb01035 小时前
C++课后习题训练记录Day74
开发语言·c++
cdut_suye5 小时前
解锁函数的魔力:Python 中的多值传递、灵活参数与无名之美
java·数据库·c++·人工智能·python·机器学习·热榜