C++ easy O(n) Time and O(1) Space


  • 0
    G
    class Solution {
    public:
        int countBinarySubstrings(string s) {
            int result = 0;       
            int l_index = 0; // Index of the last group.
            for (int i = 1; i < s.size(); ++i) {
               // If Previous element is same as this one, then we check if we can create a wider group.
                if (s[i] == s[i-1]) {
                    if (l_index - 1 >= 0 && s[l_index - 1] == s[l_index]) {
                        ++result;
                        --l_index;
                    }
                } else { // Otherwise, just reset the group to length 2 group.
                    l_index = i - 1;
                    ++result;
                }
            }
            return result;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.