1. 程式人生 > >696.Count Binary Substrings

696.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.

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

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

如果不理解,按照該程式碼自行除錯一遍,列出每次res加1所對應的子陣列方便理解。

例如 “00110”,存在連續子陣列“01”,“0011”,“10”。

Your runtime beats 25.49 % of java submissions.


 public int countBinarySubstrings(String s) {
        int prevRunLength = 0, curRunLength = 1, res = 0;
        for (int i=1;i<s.length();i++) {
            if (s.charAt(i) == s.charAt(i-1)) curRunLength++;
            else {
                prevRunLength = curRunLength;
                curRunLength = 1
; } if (prevRunLength >= curRunLength) res++; } return res; }