1016. Binary String With Substrings Representing 1 To N

Given a binary string S (a string consisting only of '0' and '1's) and a positive integer N, return true if and only if for every integer X from 1 to N, the binary representation of X is a substring of S.

Example 1:

Input: S = "0110", N = 3
Output: true

Example 2:

Input: S = "0110", N = 4
Output: false

Note:

  1. 1 <= S.length <= 1000
  2. 1 <= N <= 10^9

这个应该算暴力解法???

优化点: 由于是判断二进制是否存在,我们知道二进制左移一位等于除以2,所以如果N存在,那么N/2肯定也存在, 同理N/4,N/8,N/16都是的.

所以判断1到N是否都是子串,只要判断N到(N/2-1) 即可. N/2本身不需要判断 

class Solution {
public:
    bool queryString(string S, int N) {
        for(int i=N;i>N/2;--i)
        {
            string bin=bitset<32>(i).to_string();
            if(string::npos==S.find(bin.substr(bin.find("1"))))
                return false;
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/lychnis/p/11973922.html