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.html
Substrings that occur multiple times are counted the number of times they occur.java
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:post
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:url
s.length
will be between 1 and 50,000.s
will only consist of "0" or "1" characters.
這道題給了咱們一個二進制字符串,而後咱們統計具備相同0和1的個數,且0和1各自都羣組在一塊兒(即0和1不能交替出現)的子字符串的個數,題目中的兩個例子也很能說明問題。那麼咱們來分析題目中的第一個例子00110011,符合要求的子字符串要求0和1同時出現,那麼當第一個1出現的時候,前面因爲前面有兩個0,因此確定能組成01,再遇到下一個1時,此時1有2個,0有2個,能組成0011,下一個遇到0時,此時0的個數重置爲1,而1的個數有兩個,因此必定有10,同理,下一個還爲0,就會有1100存在,以後的也是這樣分析。那麼咱們能夠發現咱們只要分別統計0和1的個數,並且若是當前遇到的是1,那麼只要以前統計的0的個數大於當前1的個數,就必定有一個對應的子字符串,而一旦前一個數字和當前的數字不同的時候,那麼當前數字的計數要重置爲1。因此咱們遍歷元數組,若是是第一個數字,那麼對應的ones或zeros自增1。而後進行分狀況討論,若是當前數字是1,而後判斷若是前面的數字也是1,則ones自增1,不然ones重置爲1。若是此時zeros大於ones,res自增1。反之同理,若是當前數字是0,而後判斷若是前面的數字也是0,則zeros自增1,不然zeros重置爲1。若是此時ones大於zeros,res自增1。參見代碼以下:spa
解法一:code
class Solution { public: int countBinarySubstrings(string s) { int zeros = 0, ones = 0, res = 0; for (int i = 0; i < s.size(); ++i) { if (i == 0) { (s[i] == '1') ? ++ones : ++zeros; } else { if (s[i] == '1') { ones = (s[i - 1] == '1') ? ones + 1 : 1; if (zeros >= ones) ++res; } else if (s[i] == '0') { zeros = (s[i - 1] == '0') ? zeros + 1 : 1; if (ones >= zeros) ++res; } } } return res; } };
下面這種方法更加簡潔了,不用具體的分0和1的狀況來討論了,而是直接用了pre和cur兩個變量,其中pre初始化爲0,cur初始化爲1,而後從第二個數字開始遍歷,若是當前數字和前面的數字相同,則cur自增1,不然pre賦值爲cur,cur重置1。而後判斷若是pre大於等於cur,res自增1。其實核心思想跟上面的方法同樣,只不過pre和cur能夠在0和1之間切換,參見代碼以下:htm
解法二:blog
class Solution { public: int countBinarySubstrings(string s) { int res = 0, pre = 0, cur = 1, n = s.size(); for (int i = 1; i < n; ++i) { if (s[i] == s[i - 1]) ++cur; else { pre = cur; cur = 1; } if (pre >= cur) ++res; } return res; } };
相似題目:ip
參考資料:
https://discuss.leetcode.com/topic/107096/java-o-n-time-o-1-space