zoukankan      html  css  js  c++  java
  • [LeetCode] 696. 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.

    计数二进制子串。

    给定一个字符串 s,计算具有相同数量0和1的非空(连续)子字符串的数量,并且这些子字符串中的所有0和所有1都是组合在一起的。

    重复出现的子串要计算它们出现的次数。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/count-binary-substrings
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    这题 tag 是简单题但是思路不是很好想。注意题目要求的子串是既要有0也要有1,同时0和1的出现次数要相同。具体的做法是,遍历input字符串,统计每个数字连续出现的次数。举个例子,00110011,前四个数字发现有两个0两个1,所以由两个0和两个1能组成的满足提议的子串是两个(0011和中间的那对01)。按照这个思路,先统计每个数字连续出现的次数。再次遍历所有的次数,能组成的子串的数目是每两个次数中间较小的值。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int countBinarySubstrings(String s) {
     3         List<Integer> counts = new ArrayList<Integer>();
     4         int pointer = 0;
     5         int n = s.length();
     6         while (pointer < n) {
     7             char c = s.charAt(pointer);
     8             int count = 0;
     9             while (pointer < n && s.charAt(pointer) == c) {
    10                 pointer++;
    11                 count++;
    12             }
    13             counts.add(count);
    14         }
    15         int res = 0;
    16         for (int i = 1; i < counts.size(); ++i) {
    17             res += Math.min(counts.get(i), counts.get(i - 1));
    18         }
    19         return res;
    20     }
    21 }

    LeetCode 题目总结

  • 相关阅读:
    ccs元素分类 gcelaor
    webkit Safari的样式库
    “Zhuang.Data”轻型数据库访问框架(二)框架的入口DbAccessor对象
    “Zhuang.Data”轻型数据库访问框架(一)开篇介绍
    一个基于Dapper的DbContext封装
    打造比Dictionary还要快2倍以上的字查找类
    .Net core 的热插拔机制的深入探索,以及卸载问题求救指南.
    字符串类型的自动转换与识别
    最近发现的.net core中的一些bugs
    从项目经理的角度看.net的MVC中Razor语法真的很垃圾.
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13469190.html
Copyright © 2011-2022 走看看