Beautiful Binary String

Sort by

recency

|

842 Discussions

|

  • + 0 comments

    def beautifulBinaryString(b): return len(re.findall(r'(010)',b))

  • + 0 comments
    def beautifulBinaryString(n,b):
        move=0
        b=list(b)
        for i in range(n-2):
            if b[i]=='0' and b[i+1]=='1' and b[i+2]=='0':
                move+=1
                b[i+2]='1'
        return move
    
  • + 0 comments

    Here are my c++ solution, explanation here : https://youtu.be/xf0JsPRH5rs

    Solution 1 :

    int beautifulBinaryString(string b) {
        int ans = 0;
        for(int i = 0; i < b.size();){
            string sub = b.substr(i, 3);
            if(sub == "010") {
                ans++;
                i+=3;
            }else i++;
        }
        return ans;
    }
    

    Solution 2 :

    int beautifulBinaryString(string b) {
        regex re("010");
        string c = regex_replace(b, re, "");
        return (b.size() - c.size()) / 3;
    }
    
  • + 0 comments

    Java solution

     static boolean findPattern(int index, String b){
        int n = b.length();
        return (index < n - 2 && b.substring(index, index + 3).equals("010") );
        }
     
      public static int beautifulBinaryString(String b) {
        int count = 0;
        int n = b.length();
        int i = 0;
        while(i < n){
          if(findPattern(i, b)){
            count++;
            i += 3;
            }
          else
            i++;
           
          }
        return count;
        }
     
    
  • + 0 comments

    Simple C Solution

    int beautifulBinaryString(char* b) {
        int count = 0;
        int length = strlen(b);
        
        for (int i = 0; i <= length - 3; i++) {
            // Check for the substring "010"
            if (b[i] == '0' && b[i + 1] == '1' && b[i + 2] == '0') {
                count++;
                // Skip the next two characters to avoid overlapping
                i += 2; 
            }
        }
        
        return count;
    }