zoukankan      html  css  js  c++  java
  • 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都被连续分组。 发生多次的子字符串将被计数它们发生的次数。

  1. /**
  2. * @param {string} s
  3. * @return {number}
  4. */
  5. var countBinarySubstrings = function (s) {
  6. let prevRunLength = 0;
  7. let curRunLength = 1;
  8. let res = 0;
  9. for (let i = 1; i < s.length; i++) {
  10. if (s[i] == s[i - 1]) {
  11. curRunLength++;
  12. } else {
  13. prevRunLength = curRunLength;
  14. curRunLength = 1;
  15. }
  16. if (prevRunLength >= curRunLength) res++;
  17. }
  18. return res;
  19. };
  20. //console.log(countBinarySubstrings("00110011"));



来自为知笔记(Wiz)


查看全文
  • 相关阅读:
    小程序 canvas实现图片预览,图片保存
    MySQL实现排名并查询指定用户排名功能
    微信小程序canvas把正方形图片绘制成圆形
    WINDOW 安装ImageMagick服务端和PHP的imagick插件
    安装PHP扩展32位与64位的误区(x86与x64的查看)
    linux 安装 ImageMagick 和 imagick 扩展
    php 获取顶级域名
    php中通过Hashids将整数转化为唯一字符串
    yii2项目中运行composer 过程中遇到的问题
    yii2 mysql根据多个字段的数据计算排序
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7684496.html
  • Copyright © 2011-2022 走看看