领扣LintCode算法问题答案-1079. 连续子串计数
发布日期:2021-06-30 17:09:45 浏览次数:3 分类:技术文章

本文共 1360 字,大约阅读时间需要 4 分钟。

领扣LintCode算法问题答案-1079. 连续子串计数

目录

1079. 连续子串计数

描述

给定字符串s,计算有相同数量的0和1的非空连续子串的数量,并且子串中所有的0和所有的1都是连续的。

相同的子串出现多次则计数多次。

  • s.length的范围为1到50000。
  • s仅由0和1组成。

样例 1:

输入: "00110011"输出: 6解释: 有6个符合题目的连续子串:"0011", "01", "1100", "10", "0011", and "01".注意重复的子串会记录多次。而且, "00110011" 是不合理的子串,因为所有的0和1没有连在一起。

样例 2:

输入: "10101"输出: 4解释: 有4个合题的连续子串: "10", "01", "10", "01"。

题解

public class Solution {
/** * @param s: a string * @return: the number of substrings */ public int countBinarySubstrings(String s) {
// Write your code here List
countList = new ArrayList<>(); Integer currentNum = null; int startIndex = 0; for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i); int n = c - 48; if (currentNum == null) {
currentNum = n; } else {
if (currentNum != n) {
countList.add(i - startIndex); startIndex = i; currentNum = n; } } } countList.add(s.length() - startIndex); int ret = 0; for (int i = 0; i < countList.size() - 1; i++) {
ret += Math.min(countList.get(i), countList.get(i + 1)); } return ret; }}

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。

欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

转载地址:https://le-yi.blog.csdn.net/article/details/108809287 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1080. 最大的岛
下一篇:领扣LintCode算法问题答案-1078. 数组的度

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月18日 15时36分29秒