[Swift Weekly Contest 129]LeetCode1023. 子串能表示從 1 到 N 數字的二進制串 | Binary String With Substrings Representing 1 To N
阿新 • • 發佈:2019-03-24
not -i binary scala length run query present desc
Runtime: 8 ms Memory Usage: 20.4 MB
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 <= S.length <= 1000
1 <= N <= 10^9
給定一個二進制字符串 S
(一個僅由若幹 ‘0‘ 和 ‘1‘ 構成的字符串)和一個正整數 N
,如果對於從 1
到 N
的每個整數 X
,其二進制表示都是 S
的子串,就返回 true
,否則返回 false
。
示例 1:
輸入:S = "0110", N = 3 輸出:true
示例 2:
輸入:S = "0110", N = 4 輸出:false
提示:
1 <= S.length <= 1000
1 <= N <= 10^9
Runtime: 8 ms Memory Usage: 20.4 MB
1class Solution { 2 func queryString(_ S: String, _ N: Int) -> Bool { 3 if N > 2400 {return false} 4 for i in 1...N 5 { 6 var str:String = String() 7 var x:Int = i 8 while (x != 0) 9 { 10 str.append((x % 2+ 48).ASCII) 11 x /= 2 12 } 13 str = String(str.reversed()) 14 if !S.contains(str) {return false} 15 } 16 return true 17 } 18 } 19 20 //Int擴展 21 extension Int 22 { 23 //Int轉Character,ASCII值(定義大寫為字符值) 24 var ASCII:Character 25 { 26 get {return Character(UnicodeScalar(self)!)} 27 } 28 }
[Swift Weekly Contest 129]LeetCode1023. 子串能表示從 1 到 N 數字的二進制串 | Binary String With Substrings Representing 1 To N