問題:數組
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.spa
Substrings that occur multiple times are counted the number of times they occur.指針
Example 1:code
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:ip
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.解決:get
【題意】給定一個01二進制字符串,看有多少個包含0和1數目相同的子字符串,並且要求是連續的0和1,也就是說像0101這樣的不行,由於兩個0不是連續的。string
① 統計每一個連續子串的個數,如,「1111000011010001011」轉化爲「4 4 2 1 1 3 1 1 2 」,這樣咱們就能夠方便的得到知足條件的子串個數,統計轉化後的數組相鄰元素之間最小的那個求和便可。io
class Solution { //30ms
public int countBinarySubstrings(String s) {
int[] count = new int[s.length()];
int p = 0;
for (int i = 0;i < s.length() - 1;i ++){
count[p] ++;
if (s.charAt(i) != s.charAt(i + 1)){
p ++;
}
}
count[p] ++;//加上最後一個元素的處理
int res = 0;
for (int i = 0;i < p;i ++){
res += Math.min(count[i],count[i + 1]);
}
return res;
}
}class
② 使用雙指針,省去了記錄的空間,只要使用兩個變量記錄便可。
class Solution { //23ms
public int countBinarySubstrings(String s) {
int len = s.length();
if (len <= 1) return 0;
char[] schar = s.toCharArray();
int i = 0;
int pre = -1;
int res = 0;
while(i < len){
int j = i;
char c = schar[i];
while(i < len && schar[i] == c) i ++;
int cur = i - j;
if (pre != -1) res += Math.min(pre,cur);
pre = cur;
}
return res;
}
}
③ 同樣的遍歷,只是一邊遍歷,一邊記錄結果。
class Solution { //23ms public int countBinarySubstrings(String s) { if (s == null || s.length() <= 1) return 0; char[] schar = s.toCharArray(); int res = 0; char prec = schar[0]; int count = 1; int precount = 0; for (int i = 1;i < schar.length;i ++){ if (prec == schar[i]){ count ++; if (precount >= count){ res ++; } }else { precount = count; prec = schar[i]; count = 1; res ++; } } return res; } }