码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Count Binary Substrings

时间:2017-10-16 21:53:23      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:连续子数组   color   block   output   ret   否则   turn   etc   理解   

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

标签:连续子数组   color   block   output   ret   否则   turn   etc   理解   

原文地址:http://www.cnblogs.com/immjc/p/7678304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!