lintcode 1642 · クエリ文字列 [バイナリ文字列中 vip]

トピック

https://www.lintcode.com/problem/1642

给一个二进制字符串str和一个整数n,判断字符串的子串中是否包含了所有小于等于给定整数的非负整数的二进制表示。


字符串长度不超过100,000
n不超过100,000
二进制从0开始,不需要有前导0

样例
样例 1:

输入:"0110",n=3
输出:"yes"
解释:
The substring of str contains "0", "1", "10", "11".
样例 2:

输入:"0110",n=4
输出:"no"
解释:
The substring of str does not contain "100".

前提知識

	需要知道二进制的表示形式,最起码用java的自带库函数Integer.toBinaryString(数字))
	要知道,
	我的答案没有用库函数,是自己写获取数字的二进制形式,任何语言都可以这样写的

コード

public class Solution {
    
    
    /**
     * @param str: the string
     * @param n: the n
     * @return: yes or no
     */
    public String queryString(String str, int n) {
    
    
    if(!str.contains("0")) return "no";
        String s = hex2Str(n);
        if(!str.contains(s)) return "no";

        // 从 0 到 n 的布尔类型数组,true 表示二进制字符串中的子串可以表示当前数字。
        boolean[] help = new boolean[n+1];
        for (int i = n; i >=1 ; i--) {
    
    
            if(help[i]) continue; //如果之前已经认为可以被表示,则跳过
            s = hex2Str(i);
            if(!str.contains(s)) return "no";

            // 如果当前数字可以被表示,那么所有本数字所有向右位移的数字都可以被表示。
            // 直接改动 nums 数组即可。
            int tmpNum = i;
            while (tmpNum !=0){
    
    
                if(help[tmpNum]) break;
                help[tmpNum] =true;
                tmpNum >>= 1;
            }
        }
        return "yes";
    }

    //获得数字的二制表示
    public static String hex2Str(int n){
    
    
        StringBuilder sb = new StringBuilder();
        boolean start = false;
        for (int i = 31; i >=0 ; i--) {
    
    
            int a = (n & 1 << i) ==0 ?0:1;

            if(a ==1 && !start) start =true;
            if(start)
                sb.append(a+"");
        }

        return sb.toString();
    }
}

おすすめ

転載: blog.csdn.net/weixin_37991016/article/details/132789394