Suppose one encoded string S is given. We have to find and write the decoded string to a tape, here the encoded string is read one character at a time and the following steps are performed −
Now if some encoded string S, and an index K is given, find and return the K-th letter (starting indices from 1) in the decoded string.
So if the string is “hello2World3” and k = 10, then the output will be “o”. This is because the decoded string will be “hellohelloWorldhellohelloWorldhellohelloWorld”, so 10th character is “o”.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution(object): def decodeAtIndex(self, s, k): """ :type S: str :type K: int :rtype: str """ size = 0 for i in s: if i.isdigit(): size *= int(i) else: size += 1 #print(size) for i in range(len(s) - 1, -1, -1): k %= size if s[i].isalpha() and k == 0: return s[i] if s[i].isalpha(): size -=1 else: size /= int(s[i]) return "" ob = Solution() print(ob.decodeAtIndex("hello2World3", 10))
"hello2World3" 10 ob.decodeAtIndex("hello2World3", 10)