Skip to content

Latest commit

 

History

History
171 lines (133 loc) · 3.72 KB

File metadata and controls

171 lines (133 loc) · 3.72 KB

English Version

题目描述

给定一个二进制字符串 s 和一个正整数 n,如果对于 [1, n] 范围内的每个整数,其二进制表示都是 s子字符串 ,就返回 true,否则返回 false 

子字符串 是字符串中连续的字符序列。

 

示例 1:

输入:s = "0110", n = 3
输出:true

示例 2:

输入:s = "0110", n = 4
输出:false

 

提示:

  • 1 <= s.length <= 1000
  • s[i] 不是 '0' 就是 '1'
  • 1 <= n <= 109

解法

方法一:数学

4(100)存在的话,2(10)一定存在。n 存在的话,n >> 1 也一定存在,所以只需要判断 [n/2+1, n] 范围的数字。

Python3

class Solution:
    def queryString(self, s: str, n: int) -> bool:
        for i in range(n, n // 2, -1):
            if bin(i)[2:] not in s:
                return False
        return True
class Solution:
    def queryString(self, s: str, n: int) -> bool:
        return all(bin(i)[2:] in s for i in range(1, n + 1))

Java

class Solution {
    public boolean queryString(String s, int n) {
        for (int i = n; i > n / 2; i--) {
            if (!s.contains(Integer.toBinaryString(i))) {
                return false;
            }
        }
        return true;
    }
}
class Solution {
    public boolean queryString(String s, int n) {
        for (int i = 1; i <= n; ++i) {
            if (!s.contains(Integer.toBinaryString(i))) {
                return false;
            }
        }
        return true;
    }
}

Go

func queryString(s string, n int) bool {
	for i := n; i > n/2; i-- {
		if !strings.Contains(s, strconv.FormatInt(int64(i), 2)) {
			return false
		}
	}
	return true
}
func queryString(s string, n int) bool {
	for i := 1; i <= n; i++ {
		if !strings.Contains(s, strconv.FormatInt(int64(i), 2)) {
			return false
		}
	}
	return true
}

C++

class Solution {
public:
    bool queryString(string s, int n) {
        for (int i = n; i > n / 2; --i) {
            string b = bitset<32>(i).to_string();
            b = b.substr(b.find_first_not_of('0'));
            if (s.find(b) == string::npos) return false;
        }
        return true;
    }
};
class Solution {
public:
    bool queryString(string s, int n) {
        for (int i = 1; i <= n; ++i) {
            string b = bitset<32>(i).to_string();
            b = b.substr(b.find_first_not_of('0'));
            if (s.find(b) == string::npos) return false;
        }
        return true;
    }
};

TypeScript

function queryString(s: string, n: number): boolean {
    for (let i = 1; i <= n; ++i) {
        if (s.indexOf(i.toString(2)) === -1) {
            return false;
        }
    }
    return true;
}

...