Leetcode 696 Count Binary Substrings
2018-01-31 21:25
246 查看
Leetcode 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, an 4000 d 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.
一道easy题想的挺久的。。。
思路
按顺序统计字符串中连续出现‘1’和‘0’的个数,按顺序分别保存在一个数组中。最终结果就是这个数组两两相邻的数中最小的数的和。对于‘00110011’,该数组为2,2,2,2
所以答案是 2 + 2 + 2 = 6
对于‘00100110’,该数组为2,1,2,2,1
所以答案是 1 + 1 + 2 + 1 = 5
代码
class Solution { public int countBinarySubstrings(String s) { int sum = 0; // 只需要记录前一个不同元素的个数即可,不必保存所有个数 int prev = 0, cur = 1; for (int i = 1; i < s.length(); ++i) { if (s.charAt(i) == s.charAt(i - 1)) { cur++; } else { if (prev != 0) sum += prev < cur ? prev : cur; prev = cur; cur = 1; } } // 最后相邻的数要记得比较 return sum + (prev < cur ? prev : cur); } }
相关文章推荐
- LeetCode-696-Count Binary Substringss-E
- leetcode 696 Count Binary Substrings
- leetcode Count and Say
- Leetcode: Count Complete Tree Nodes
- LeetCode-38-Count and Say Python的int_to_string
- [Leetcode]Count and Say
- leetcode 题解 Count Primes
- Count and Say -- LeetCode
- leetcode-Count and Say
- LeetCode--No.38--Count and Say
- [LeetCode][JavaScript]Count of Smaller Numbers After Self
- LeetCode 38 Count and Say
- [leetcode-222]Count Complete Tree Nodes(c)
- leetcode 038 —— Count and Say
- leetcode 038 Count and Say
- Leetcode 222 Count Complete Tree Nodes 完全二叉树的结点数
- Leetcode Count of Smaller Numbers After Self
- Leetcode Count Primes
- Leetcode177: Count Complete Tree Nodes
- leetcode 600 Count number of binary strings without consecutive 1 不出现连续1二进制数量