Leetcode 916 Solution

This article provides solution to leetcode question 916 (decoded-string-at-index)

https://leetcode.com/problems/decoded-string-at-index

Solution

class Solution(object):
    def decodeAtIndex(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        size = 0
        for ch in S:
            if ch.isdigit():
                size *= int(ch)
            else:
                size += 1

        for ch in reversed(S):
            K %= size

            if K == 0 and ch.isalpha():
                return ch

            if ch.isdigit():
                size /= int(ch)
            else:
                size -= 1