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

相关推荐
TimberWill1 小时前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit1 小时前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung1 小时前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
OliverH-yishuihan1 小时前
开发linux项目-在 Windows 上 基于“适用于 Linux 的 Windows 子系统(WSL)”
linux·c++·windows
七禾页丫2 小时前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
zmzb01033 小时前
C++课后习题训练记录Day56
开发语言·c++
编程小Y3 小时前
C++ Insights
开发语言·c++
王老师青少年编程4 小时前
csp信奥赛C++标准模板库STL案例应用5
c++·stl·set·集合·标准模板库·csp·信奥赛
历程里程碑4 小时前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
Tipriest_4 小时前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法