Leetcode 872 Solution

This article provides solution to leetcode question 872 (split-array-into-fibonacci-sequence)

https://leetcode.com/problems/split-array-into-fibonacci-sequence

Solution

class Solution(object):
    def splitIntoFibonacci(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        i = 1
        limit = 2**31 - 1

        while i < len(S):
            j = i + 1

            while j < len(S):
                sa = S[:i]
                sb = S[i:j]

                ia = int(sa)
                ib = int(sb)

                if str(ia) != sa or str(ib) != sb:
                    j += 1
                    continue

                ans = [ia, ib]
                k = j
                while k < len(S):
                    ic = ia + ib
                    sc = str(ic)

                    if ia > limit or ib > limit:
                        break

                    if sc != S[k:k + len(sc)]:
                        break

                    k += len(sc)
                    ia = ib
                    ib = ic
                    ans.append(ic)

                if k == len(S) and ic <= limit:
                    return ans

                j += 1

            i += 1

        return []