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

前端 未结 30 2962
刺人心
刺人心 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:30

    I came up with something like this:

    def IsSymetric(number):
        number = number.strip('0')
    
        if len(number) < 3:
            return False
        if len(number) % 2 == 0:
            return IsSymetric(number[1:]) or IsSymetric(number[0:len(number)-2])
        else:
            if number[len(number)//2] == '1':
                return True
            return IsSymetric(number[:(len(number)//2)]) or IsSymetric(number[len(number)//2+1:])
        return False
    

    This is inspired by andycjw.

    1. Truncate the zeros.
    2. If even then test two substring 0 - (len-2) (skip last character) and from 1 - (len-1) (skip the first char)
    3. If not even than if the middle char is one than we have success. Else divide the string in the midle without the midle element and check both parts.

    As to the complexity this might be O(nlogn) as in each recursion we are dividing by two.

    Hope it helps.

提交回复
热议问题