美文网首页
696. Count Binary Substrings

696. Count Binary Substrings

作者: DrunkPian0 | 来源:发表于2017-10-15 11:05 被阅读24次

https://leetcode.com/contest/leetcode-weekly-contest-54/problems/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.
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.

做这种题目好比做阅读理解...读懂题目就写出来了..溜了溜了

    public int countBinarySubstrings(String s) {
        if (s == null) return 0;
        int res = 0;
        for (int i = 0; i < s.length() - 1; i++) {
            if (isAvailable(s, i)) {
                res++;
            }
        }
        return res;
    }

    private boolean isAvailable(String s, int index) {
        int origin = s.charAt(index);
        int len = 0;
        int i;
        for (i = index + 1; i < s.length(); i++) {
            if (s.charAt(i) != origin) {
                len = i - index;
                break;
            }
        }
        if (len == 0) return false;
        for (int j = i; j < s.length(); j++) {
            if (s.charAt(j) == origin) {
                break;
            }
            len--;
            if (len == 0) break;
        }
        return len == 0;
    }

相关文章

网友评论

      本文标题:696. Count Binary Substrings

      本文链接:https://www.haomeiwen.com/subject/legquxtx.html