- Trending Categories
- Data Structure
- Operating System
- C Programming
- 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 −
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)
- Find the character in first string that is present at minimum index in second string in Python
- Even numbers at even index and odd numbers at odd index in C++
- Program to find out the letter at a particular index in a synthesized string in python
- Index Pairs of a String in Python
- Index into an Infinite String in Python
- Python Pandas - Insert a new index value at the first index from the last
- String at () in C++
- Python Pandas - Insert a new index value at a specific position
- Return the lowest index in the string where substring is found using Python index()
- Update object at specific Array Index in MongoDB?
- Java Program to get a character located at the String's specified index
- Python Pandas - Calculate TimedeltaArray of difference between index values and index converted to PeriodArray at specified freq
- Golang Program to update the ith index node value, when index is at 0 index.