O(nlogn) Algorithm - Find three evenly spaced ones within binary string

前端 未结 30 3020
刺人心
刺人心 2020-11-28 00:07

I had this question on an Algorithms test yesterday, and I can\'t figure out the answer. It is driving me absolutely crazy, because it was worth about 40 points. I figure

30条回答
  •  一个人的身影
    2020-11-28 00:54

    I'll give my rough guess here, and let those who are better with calculating complexity to help me on how my algorithm fares in O-notation wise

    1. given binary string 0000010101000100 (as example)
    2. crop head and tail of zeroes -> 00000 101010001 00
    3. we get 101010001 from previous calculation
    4. check if the middle bit is 'one', if true, found valid three evenly spaced 'ones' (only if the number of bits is odd numbered)
    5. correlatively, if the remained cropped number of bits is even numbered, the head and tail 'one' cannot be part of evenly spaced 'one',
    6. we use 1010100001 as example (with an extra 'zero' to become even numbered crop), in this case we need to crop again, then becomes -> 10101 00001
    7. we get 10101 from previous calculation, and check middle bit, and we found the evenly spaced bit again

    I have no idea how to calculate complexity for this, can anyone help?

    edit: add some code to illustrate my idea

    edit2: tried to compile my code and found some major mistakes, fixed

    char *binaryStr = "0000010101000100";
    
    int main() {
       int head, tail, pos;
       head = 0;
       tail = strlen(binaryStr)-1;
       if( (pos = find3even(head, tail)) >=0 )
          printf("found it at position %d\n", pos);
       return 0;
    }
    
    int find3even(int head, int tail) {
       int pos = 0;
       if(head >= tail) return -1;
       while(binaryStr[head] == '0') 
          if(head= tail) return -1;
       if( (tail-head)%2 == 0 && //true if odd numbered
           (binaryStr[head + (tail-head)/2] == '1') ) { 
             return head;
       }else {
          if( (pos = find3even(head, tail-1)) >=0 )
             return pos;
          if( (pos = find3even(head+1, tail)) >=0 )
             return pos;
       }
       return -1;
    }
    

提交回复
热议问题