Problem
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.
ExampleExample 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.
public class Solution { /** * @param s: a string * @return: the number of substrings */ public int countBinarySubstrings(String s) { // Write your code here int countZero = 0, countOne = 0, result = 0; char[] str = s.toCharArray(); for (int i = 0; i < str.length; i++) { if (i == 0) { if (str[i] == "0") { countZero++; } else countOne++; } else { if (str[i] == "0") { if (str[i-1] == "0") countZero++; else countZero = 1; if (countOne >= countZero) result++; } else { if (str[i-1] == "1") countOne++; else countOne = 1; if (countZero >= countOne) result++; } } } return result; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/71631.html
摘要:首先將兩個字符串化成字符數組,排序后逐位比較,確定它們等長且具有相同數量的相同字符。然后,從第一個字符開始向后遍歷,判斷和中以這個坐標為中點的左右兩個子字符串是否滿足第一步中互為的條件設分為和,分為和。 Problem Given a string s1, we may represent it as a binary tree by partitioning it to two no...
摘要:則不算,因為兩個被分割開了,不是連續的。思路只記錄前一組是還是,以及出現的次數。相同,則判斷是否與前一個字符相同。那么此時需要拋棄前一組的所有內容。當前一組未配對字符數量達到時,說明前一組已經沒有可以匹配的字符。故把當前組替換未前一組。 D88 696. Count Binary Substrings 題目鏈接 696. Count Binary Substrings 題目分析 給定一...
Problem Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of the subtree have the same value. Example Given root = {5,1,5,5,5,#,5}, return 4. 5...
摘要:根據二叉平衡樹的定義,我們先寫一個求二叉樹最大深度的函數。在主函數中,利用比較左右子樹的差值來判斷當前結點的平衡性,如果不滿足則返回。 Problem Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as...
Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...
閱讀 3270·2021-10-11 10:59
閱讀 2836·2021-10-11 10:58
閱讀 2246·2021-09-04 16:45
閱讀 2724·2019-08-30 15:44
閱讀 678·2019-08-30 15:44
閱讀 3206·2019-08-30 10:51
閱讀 1602·2019-08-29 18:46
閱讀 2758·2019-08-29 13:57