zoukankan      html  css  js  c++  java
  • [LeetCode] Count Binary Substrings

    Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.

    Substrings that occur multiple times are counted the number of times they occur.

    Example 1:

    Input: "00110011"
    Output: 6
    Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
    
    Notice that some of these substrings repeat and are counted the number of times they occur.
    Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.

    Example 2:

    Input: "10101"
    Output: 4
    Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

    Note:

    • s.length will be between 1 and 50,000.
    • s will only consist of "0" or "1" characters.

    给定一个由0和1组成的非空字符串,计算出由相同0和1且0和1分别连续的子串的个数。子串可以重复。

    思路:使用2个变量来存储当前数字前的数字连续次数pre以及当前数字的连续次数cur。如果当前数字与前一个数字连续,则计算出当前数字连续的次数cur,否则统计当前数字之前的数字连续次数pre并令当前数字连续次数cur为1。接着通过判断统计子数组的个数,如果这时该数字之前的数字连续次数pre大于等于当前数字连续次数cur,则令子数组个数res加1。

    如果不理解,按照该代码自行调试一遍,列出每次res加1所对应的子数组方便理解。

    例如 “00110”,存在连续子数组“01”,“0011”,“10”。

    class Solution {
    public:
        int countBinarySubstrings(string s) {
            int pre = 0, cur = 1, res = 0;
            for (int i = 1; i != s.size(); i++) {
                if (s[i] == s[i - 1]) {
                    cur++;
                }
                else {
                    pre = cur;
                    cur = 1;
                }
                if (pre >= cur)
                    res++;
            }
            return res;
        }
    };
    // 42 ms
  • 相关阅读:
    Basic4android v3.20 发布
    KbmMW 4.40.00 正式版发布
    Devexpress VCL Build v2013 vol 13.2.2 发布
    KbmMW 4.40.00 测试发布
    kbmMWtable for XE5 接近尾声
    使用delphi 开发多层应用(二十一)使用XE5 RESTClient 直接访问kbmmw 数据库
    为什么有些东西,反反复复总是学不会
    心灵沟通
    <转>离婚前夜悟出的三件事
    c++ socket 客户端库 socks5 客户端 RudeSocket™ Open Source C++ Socket Library
  • 原文地址:https://www.cnblogs.com/immjc/p/7678304.html
Copyright © 2011-2022 走看看