首页 > 其他 > 详细

1016. Binary String With Substrings Representing 1 To N

时间:2019-12-03 01:00:19      阅读:107      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

1016. Binary String With Substrings Representing 1 To N

原文:https://www.cnblogs.com/lychnis/p/11973922.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!