
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
Find K-th Character of Decrypted String in Python
Suppose we have one encoded string where repetitions of substrings are represented as substring followed by count of substrings. As an example, if the string is "pq2rs2" and k=5, so output will be 'r', this is because the decrypted string is "pqpqrsrs" and 5th character is 'r'. We have to keep in mind that the frequency of encrypted substring can be of more than one digit.
So, if the input is like string = "pq4r2ts3" and k = 11, then the output will be i, as the string is pqpqpqpqrrtststs
To solve this, we will follow these steps −
encoded := blank string
occurrence := 0, i := 0
-
while i < size of str, do
temp := blank string
occurrence := 0
-
while i < size of str and str[i] is an alphabet, do
temp := temp + str[i]
i := i + 1
-
while i < size of str and str[i] is a digit, do
occurrence := occurrence * 10 + ASCII of (str[i]) - ASCII of ('0')
i := i + 1
-
for j in range 1 to occurrence + 1, increase by 1, do
encoded := encoded + temp
-
if occurrence is same as 0, then
encoded := encoded + temp
return encoded[k - 1]
Example
Let us see the following implementation to get better understanding −
def find_kth_char(str, k): encoded = "" occurrence = 0 i = 0 while i < len(str): temp = "" occurrence = 0 while (i < len(str) and ord(str[i]) >= ord('a') and ord(str[i]) <= ord('z')): temp += str[i] i += 1 while (i < len(str) and ord(str[i]) >= ord('1') and ord(str[i]) <= ord('9')): occurrence = occurrence * 10 + ord(str[i]) - ord('0') i += 1 for j in range(1, occurrence + 1, 1): encoded += temp if occurrence == 0: encoded += temp return encoded[k - 1] str = "pq4r2ts3" k = 11 print(find_kth_char(str, k))
Input
"pq4r2ts3", 11
Output
t