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
  • 相关阅读:
    AndroidUI的组成部分ProgressBar
    NVIDIA+关联2015写学校招收评论(嵌入式方向,上海)
    谈论json
    排序算法(三):插入排序
    逻辑地址、线性地址、物理地址以及虚拟存储器
    逻辑地址、线性地址和物理地址的关系
    堆和栈都是虚拟地址空间上的概念
    缺页异常详解
    虚拟内存-插入中间层思想
    深入理解计算机系统之虚拟存储器
  • 原文地址:https://www.cnblogs.com/immjc/p/7678304.html
Copyright © 2011-2022 走看看