• LeetCode 696 计数二进制子串


    Leetcode 696 计数二进制子串

    给定一个只包含0,1的字符串,假设一个连续子串中若包含相同数量的0,1且不交错分布则为一个满足要求的子串,求给定字符串中有多少个满足要求的子串。
    方法: 交替对连续的0,1子串进行计数。当已经计数有last个连续的0时,若接下来又计数有count个连续的1,则last个0、count个1组成的子串中满足要求的子串一共有min(last, count)个

    执行用时:10 ms, 在所有 Java 提交中击败了87.83%的用户
    内存消耗:40.2 MB, 在所有 Java 提交中击败了61.54%的用户

    class Solution { 
        public int countBinarySubstrings(String s) {
            int ptr = 0, n = s.length(), last = 0, ans = 0;
            while (ptr < n) {
                //c记录每一次记录的子串元素
                char c = s.charAt(ptr);
                //记录当前子串中相同字符c的数量
                int count = 0;
                while (ptr < n && s.charAt(ptr) == c) {
                    ++ptr;
                    ++count;
                }
                //结果值更新
                ans += Math.min(count, last);
                last = count;
            }
            return ans;
        }
    }
    
  • 相关阅读:
    Line of Sight 计算几何基础
    Hash算法详解
    高效mysql的习惯(程序员版本)
    thymeleaf初步使用
    @Transactional注解事务不起作用
    泛型的理解
    Git&GitHun 命令合集
    springboot引入thymeleaf
    springboot静态资源映射
    springboot的配置文件
  • 原文地址:https://www.cnblogs.com/CodeSPA/p/13471889.html
Copyright © 2020-2023  润新知