1. 程式人生 > >[LeetCode] Count Binary Substrings

[LeetCode] Count Binary Substrings

out style ted 一個 bin between 以及 tco rac

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.

給定一個由0和1組成的非空字符串,計算出由相同0和1且0和1分別連續的子串的個數。子串可以重復。

思路:使用2個變量來存儲當前數字前的數字連續次數pre以及當前數字的連續次數cur。如果當前數字與前一個數字連續,則計算出當前數字連續的次數cur,否則統計當前數字之前的數字連續次數pre並令當前數字連續次數cur為1。接著通過判斷統計子數組的個數,如果這時該數字之前的數字連續次數pre大於等於當前數字連續次數cur,則令子數組個數res加1。

如果不理解,按照該代碼自行調試一遍,列出每次res加1所對應的子數組方便理解。

例如 “00110”,存在連續子數組“01”,“0011”,“10”。

class Solution {
public:
    int countBinarySubstrings(string s) {
        int pre = 0, cur = 1, res = 0;
        for (int i = 1; i != s.size(); i++) {
            if (s[i] == s[i - 1]) {
                cur++;
            }
            
else { pre = cur; cur = 1; } if (pre >= cur) res++; } return res; } }; // 42 ms

[LeetCode] Count Binary Substrings