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

相关推荐
apcipot_rain5 小时前
C++转Java日记(04)
java·开发语言·c++
WL学习笔记7 小时前
vector模拟实现
c++
蜗牛一步步往上爬9 小时前
第十六章 C++语言在深度学习中的应用
开发语言·c++·深度学习
文丑颜不良啊12 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z13 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
wo_jack13 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
D e re k ZH13 小时前
C++ 标准库算法全景指南
数据结构·c++·算法
文丑颜不良啊14 小时前
LeetCode2161~2180题目解析
java·leetcode
雪落漂泊15 小时前
C++算法 二分查找篇(上)
开发语言·c++·算法
不会算法的笨小孩16 小时前
异常的使用以及会出现的问题
开发语言·c++·c++11·异常