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)。

相关推荐
kk哥88991 天前
C++ 对象 核心介绍
java·jvm·c++
helloworddm1 天前
WinUI3 主线程不要执行耗时操作的原因
c++
YoungHong19921 天前
面试经典150题[072]:从前序与中序遍历序列构造二叉树(LeetCode 105)
leetcode·面试·职场和发展
无能者狂怒1 天前
YOLO C++ Onnx Opencv项目配置指南
c++·opencv·yolo
im_AMBER1 天前
Leetcode 78 识别数组中的最大异常值 | 镜像对之间最小绝对距离
笔记·学习·算法·leetcode
集智飞行1 天前
c++函数传参的几种推荐方式
开发语言·c++
LYFlied1 天前
【每日算法】LeetCode 25. K 个一组翻转链表
算法·leetcode·链表
点云SLAM1 天前
C++ Template(模板)解读和模板报错如何“逆向阅读”定位
c++·c++20·c++模版·c++高级应用·c++模版报错定位
明洞日记1 天前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
农夫山泉2号1 天前
【c++】——c++编译的so中函数有额外的字符
java·服务器·c++