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

相关推荐
Coding小公仔1 小时前
C++ bitset 模板类
开发语言·c++
凌肖战1 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
菜鸟看点1 小时前
自定义Cereal XML输出容器节点
c++·qt
悲伤小伞3 小时前
linux_git的使用
linux·c语言·c++·git
ysa0510303 小时前
数论基础知识和模板
数据结构·c++·笔记·算法
GEEK零零七3 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
重庆小透明5 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq5 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
小小小小王王王6 小时前
求猪肉价格最大值
数据结构·c++·算法
岁忧6 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go