
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Decoded String at Index in Python
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 −
- If the character read is a letter, that letter is simply written onto the tape.
- If the character read is a digit, the entire current tape is repeatedly written digit – 1 more times in total.
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 −
- size := 0
- for i in string s
- if i is a numeric character, then size := size * integer from of i, otherwise size := size + 1
- for i in range length of s – 1 down to 0
- k := k mod size
- if s[i] is numeric and k = 0, then return s[i]
- if s[i] is numeric, then decrease size by 1, otherwise size := size / integer of s[i]
- return empty string
Let us see the following implementation to get better understanding −
Example
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))
Input
"hello2World3" 10 ob.decodeAtIndex("hello2World3", 10)
Output
o
Advertisements