• [LeetCode] 1461. Check If a String Contains All Binary Codes of Size K


    Given a binary string s and an integer k.

    Return True if every binary code of length k is a substring of s. Otherwise, return False.

    Example 1:

    Input: s = "00110110", k = 2
    Output: true
    Explanation: The binary codes of length 2 are "00", "01", "10" and "11". They can be all found as substrings at indicies 0, 1, 3 and 2 respectively.
    

    Example 2:

    Input: s = "00110", k = 2
    Output: true
    

    Example 3:

    Input: s = "0110", k = 1
    Output: true
    Explanation: The binary codes of length 1 are "0" and "1", it is clear that both exist as a substring. 
    

    Example 4:

    Input: s = "0110", k = 2
    Output: false
    Explanation: The binary code "00" is of length 2 and doesn't exist in the array.
    

    Example 5:

    Input: s = "0000000001011100", k = 4
    Output: false

    Constraints:

    • 1 <= s.length <= 5 * 10^5
    • s consists of 0's and 1's only.
    • 1 <= k <= 20

    检查一个字符串是否包含所有长度为 K 的二进制子串。

    给你一个二进制字符串 s 和一个整数 k 。

    如果所有长度为 k 的二进制字符串都是 s 的子串,请返回 True ,否则请返回 False 。

    这道题问的是在字符串中是否能找到所有长度为 K 的二进制子串,应该不难想到需要用滑动窗口做,但是这里有一个很巧妙的处理,能快速知道你到底需要找多少个子串。因为子串的长度是 K,所以一共需要找 Math.pow(2, k) 个子串。所以这里我们利用一个hashset,如果遍历完input字符串之后set.size() == k则证明找全了,否则就是有缺失。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public boolean hasAllCodes(String s, int k) {
     3         HashSet<String> set = new HashSet<>();
     4         for (int i = k; i <= s.length(); i++) {
     5             set.add(s.substring(i - k, i));
     6             if (set.size() > (1 << k)) {
     7                 break;
     8             }
     9         }
    10         return set.size() == 1 << k;
    11     }
    12 }

    LeetCode 题目总结

  • 相关阅读:
    设计模式-单例模式
    Java对象声明时:new与null的区别
    Mysql的UseAffectedRows问题 以及其他常见配置说明
    将form表单元素的值序列化成对象
    idea教程视频以及常用插件整理
    Ajax获取Response头信息
    BootstrapTable返回结果集递增序号
    mybaitis动态sql利用bind标签代替%拼接完成模糊查询
    Numpy库使用
    基于socket实现websocket服务
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14531296.html
Copyright © 2020-2023  润新知