[字符串] leetcode 1016 Binary String With Substrings Representing 1 To N

problem:https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/

        暴力枚举了一下所有子字符串可能对应的数字,统计是否达到N个,就过了。不知道有没有更快的方法。

class Solution {
public:
    bool queryString(string S, int N) {
        unordered_set<int> count;
        for(int i = 0;i < S.size();i++)
        {
            if(S[i] == '0') continue;
            int num = 0;
            for(int j = i;j < S.size();j++)
            {
                num = 2 * num + S[j] - '0';
                
                if(num <= N)
                {
                    count.insert(num);
                }
                else
                {
                    break;
                }
            }
        }
        return count.size() == N;
    }
};

 

posted @ 2019-08-03 17:14  fish1996  阅读(125)  评论(0编辑  收藏  举报