LeetCode - Easy - 696. Count Binary Substrings

Topic

  • String

Description

https://leetcode.com/problems/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.

Analysis

方法一:暴力算法,遇到超长字符串会超时,故弃。

方法二:发现字符串其中规律

  1. 如’00000111’,一个连续’0’与连续’1’的字符串,符合题意要求的子字符串为min('0‘的个数, '1’的个数)=min(5,3)=3。
  2. 如’000011100111‘字符串,以连续相同字符分为一个区间规则,得到[0,3],[4,6],[7,8],[9,11]共4个区间。
  3. 由2. 得到区间,将其两两相邻配对,如[0,3]与[4,6],[4,6]与[7,8],再由1. 得出规律求出两配对区间符合题意要求的子字符串个数,最后将其累加,便能得到最后结果。

方法三:方法二改进版。

Submission

import java.util.ArrayList;
import java.util.List;public class CountBinarySubstrings {// 方法一:暴力算法,遇到超长字符串会超时public int countBinarySubstrings(String s) {int result = 0;// List<String> resultList = new ArrayList<>();for (int i = 0; i < s.length(); i++) {int state = 1;char tempChar = s.charAt(i);int firstCharCount = 1, secondCharCount = 0, rightPartCount = 0;for (int j = i + 1; j < s.length(); j++) {if (state == 1) {if (tempChar == s.charAt(j)) {firstCharCount++;} else {state = 2;tempChar = s.charAt(j);}}if (state == 2) {if (tempChar == s.charAt(j)) {secondCharCount++;}rightPartCount++;if (rightPartCount == firstCharCount) {if (secondCharCount == firstCharCount) {result++;// resultList.add(repeat(tempChar=='1'?'0':'1', firstCharCount) +// repeat(tempChar, secondCharCount));}break;}}}}return result;}// 方法二:public int countBinarySubstrings2(String s) {List<int[]> list = new ArrayList<>();int result = 0, tempIndex = 0;for (int i = tempIndex + 1; i <= s.length(); i++) {if (i == s.length() || s.charAt(i) != s.charAt(tempIndex)) {list.add(new int[] { tempIndex, i - 1 });tempIndex = i;}}for (int i = 0; i < list.size(); i++) {int[] leftPart = list.get(i);if (i + 1 == list.size()) {break;}int[] rightPart = list.get(i + 1);int leftSize = leftPart[1] - leftPart[0] + 1;int rightSize = rightPart[1] - rightPart[0] + 1;result += Math.min(leftSize, rightSize);}return result;}// 方法三:方法二的改进版public int countBinarySubstrings3(String s) {int result = 0, lastIndex = 0, lastSize = 0;for (int i = lastIndex + 1; i <= s.length(); i++) {if (i == s.length() || s.charAt(i) != s.charAt(lastIndex)) {if (lastSize == 0) {lastSize = i - lastIndex;} else {int currentSize = i - lastIndex;result += Math.min(lastSize, currentSize);lastSize = currentSize;}lastIndex = i;}}return result;}private String repeat(char c, int times) {StringBuilder sb = new StringBuilder();for (int i = 0; i < times; i++) {sb.append(c);}return sb.toString();}}

Test

import static org.junit.Assert.*;
import org.junit.Test;public class CountBinarySubstringsTest {@Testpublic void test() {CountBinarySubstrings obj = new CountBinarySubstrings();assertEquals(6, obj.countBinarySubstrings("00110011"));assertEquals(4, obj.countBinarySubstrings("10101"));}@Testpublic void test2() {CountBinarySubstrings obj = new CountBinarySubstrings();assertEquals(6, obj.countBinarySubstrings2("00110011"));assertEquals(4, obj.countBinarySubstrings2("10101"));}@Testpublic void test3() {CountBinarySubstrings obj = new CountBinarySubstrings();assertEquals(0, obj.countBinarySubstrings3("00"));assertEquals(1, obj.countBinarySubstrings3("001"));assertEquals(6, obj.countBinarySubstrings3("00110011"));assertEquals(4, obj.countBinarySubstrings3("10101"));assertEquals(3, obj.countBinarySubstrings3("00110"));}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/445681.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MySQL优化学习笔记

----一、MySQL架构介绍-01_课程简介02_MySQL简介03_RPM安装04_ROOT密码设置和开机自启动05_安装位置06_修改字符集07_MySQL配置文件08_MySQL逻辑架构简介09_存储引擎简介-二、索引优化分析-10_SQL性能下降原因11_SQL执行加载顺序12_七种JOIN理论13_七种JOIN的SQL编写14_索引是什…

回溯算法学习笔记

学习资料来源 代码随想录 - 关于回溯算法&#xff0c;你该了解这些&#xff01; 什么是回溯法 回溯&#xff08;backtracking&#xff09;法又称回溯搜索法&#xff0c;它是一种搜索的方式。 回溯法不容易&#xff0c;但回溯法就是暴力解法。 回溯与递归形影不离。 backtra…

Java中int[]与Integer[]相互转化的方法

传统方法 //Convert int[] to Integer[] public static Integer[] toObject(int[] intArray) {Integer[] result new Integer[intArray.length];for (int i 0; i < intArray.length; i) {result[i] Integer.valueOf(intArray[i]);}return result; }//Convert Integer[] …

《UNIX环境高级编程 3rd》笔记(1 / 21):UNIX基础知识

文章目录引言UNIX体系结构登录登录名shell文件和目录文件系统文件名路径名工作目录起始目录输入和输出文件描述符标准输入、标准输出和标准错误不带缓冲的IO标准IO程序和进程程序进程和进程ID进程控制线程和线程ID出错处理出错恢复用户标识用户ID组ID附属组ID信号时间值系统调用…

《集体智慧编程》笔记(1 / 12):集体智慧导言

文章目录什么是集体智慧什么是机器学习机器学习的局限性真实生活中的例子学习型算法的其他用途小结Netflix, Google都适用了先进算法&#xff0c;将来自不同人群的数据加以组合&#xff0c;进而得出新的结论&#xff0c;并创造新的商机。 更多类似例子&#xff1a; 约会网站希…

《集体智慧编程》笔记(2 / 12):提供推荐

Making Recommendations 文章目录协作型过滤搜集偏好寻找相近的用户欧几里得距离评价皮尔逊相关度评价应该选用哪一种相似性度量方法为评分者打分推荐物品匹配相似商品构建一个基于某数据平台的链接推荐系统数据平台API构造数据集推荐近邻与链接基于物品的过滤构造物品比较数据…

LeetCode - Easy - 637. Average of Levels in Binary Tree

Topic Tree Description https://leetcode.com/problems/average-of-levels-in-binary-tree/ Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10−510^{-5}10−5 of the actual answer w…

在CodeBlocks下配置GoogleTest单元测试框架

环境准备 Windows 10Code::Blocks 20.03Google Test 1.7.0CMake 3.11.0 编译GoogleTest 一、创建一个工作目录D:\gtest&#xff0c;将刚下载的Google Test 1.7.0、CMake 3.11.0的压缩包解压到刚创建的工作目录。 二、进入CMake文件夹的bin下&#xff0c;运行cmake-gui.exe&…

傻子都能看懂的马拉车Manacher

Manachers Algorithm 马拉车算法操作及原理 package advanced_001;public class Code_Manacher {public static char[] manacherString(String str) {char[] charArr str.toCharArray();char[] res new char[str.length() * 2 1];int index 0;for (int i 0; i ! res.len…

简单暴力到dp的优化(萌新篇)

想写一系列文章&#xff0c;总结一些题目&#xff0c;看看解决问题、优化方法的过程到底是什么样子的。 系列问题一&#xff1a;斐波那契数列问题 在数学上&#xff0c;斐波纳契数列以如下被以递归的方法定义&#xff1a;F(0)0&#xff0c;F(1)1, F(n)F(n-1)F(n-2)&#xff08…

LeetCode - Medium - 114. Flatten Binary Tree to Linked List

Topic TreeDepth-first Search Description https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ Given the root of a binary tree, flatten the tree into a “linked list”: The “linked list” should use the same TreeNode class where the right…

简单暴力到dp的优化(入门篇)

上篇&#xff0c;我们提到&#xff0c;遇到问题&#xff0c;首先根据定义写出笨方法&#xff0c;找出依赖关系&#xff08;有些题这一步就不太简单&#xff0c;要自己归纳关系&#xff09;&#xff0c;然后进行优化&#xff0c;下面&#xff0c;我们通过几道此方面的经典的&…

简单暴力到dp的优化(初级篇)

一、一维非脑残 1 一个只包含A、B和C的字符串&#xff0c;如果存在某一段长度为3的连续子串中恰好A、B和C各有一个&#xff0c;那么这个字符串就是纯净的&#xff0c;否则这个字符串就是暗黑的。例如&#xff1a;BAACAACCBAAA 连续子串"CBA"中包含了A,B,C各一个&am…

ccpc河北大学生程序设计竞赛dp小总结

近期题目来自校赛&#xff0c;赛前训练&#xff0c;省赛热身&#xff0c;河北ccpc正式比赛。 题目一&#xff1a; 题目描述&#xff1a; 由于第m个台阶上有好吃的薯条&#xff0c;所以薯片现在要爬一段m阶的楼梯. 薯片每步最多能爬k个阶梯&#xff0c;但是每到了第i个台阶&a…

c语言简便实现链表增删改查

注&#xff1a;单追求代码简洁&#xff0c;所以写法可能有点不标准。 //第一次拿c开始写数据结构&#xff0c;因为自己写的&#xff0c;追求代码量少&#xff0c;和学院ppt不太一样。有错请指出 #include <stdio.h> #include <stdlib.h> #include <string.h>…

第一次课 课上代码

第一次课内容 学习心态及注意事项 信心 谦虚 脚踏实地 多动手 python简介 代码量少&#xff0c;简介&#xff0c;易上手&#xff0c;语法要求不过于严格&#xff0c; Python 库。 速度慢&#xff0c; 不可加密。 输出、变量、输入 数据类型&#xff1a;整数、浮点数…

计算机考研专业课只考一科的学校汇总

下列学校专业课只考1门 &#xff08;每项科目下的学校均按照最新学科评估结果由高到低进行排名&#xff09; C语言程序设计 1. 湖南大学 计算机技术&软工专硕&#xff08;信息科学与工程学院&#xff09; 2. 中国海洋大学 计算机技术&#xff08;01计算机应用技术方向&am…

数组实现栈

学习了改进&#xff0c;利用define typedef比上次写的链表更容易改变功能&#xff0c;方便维护&#xff0c;代码更健壮。 大佬别嫌弃&#xff0c;萌新总是很笨&#xff0c;用typedef都想不到。 #include<stdio.h> #include<stdbool.h> #define maxsize 10 typede…

简单暴力到dp的优化(中级篇)

下面再放三道我比较喜欢的&#xff0c;需要好好写一下的题。 第一题比较水 1. White Cloud is exercising in the playground. White Cloud can walk 1 meters or run k meters per second. Since White Cloud is tired,it cant run for two or more continuous seconds. Whi…

第二次课 课上代码

敲一遍&#xff0c;体会每行代码想表达的意思。 第二讲 创建.py文件 数据类型&#xff1a;布尔(and\or\not) 条件判断语句(if elif else) 列表基础操作&#xff08;特点、创建、增加元素、len()、下标、py切片&#xff09; >>> 5>4 True >>> 4>5 Fa…