An encoded string S
is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken:
- If the character read is a letter, that letter is written onto the tape.
- If the character read is a digit (say
d
), the entire current tape is repeatedly writtend-1
more times in total.
Now for some encoded string S
, and an index K
, find and return the K
-th letter (1 indexed) in the decoded string.
Example 1:
Input: S = "ha22", K = 5 Output: "h"
Approach
Java
public class DecodedStringIndex {public static void main(String[] args) {String S = "ha22";int K = 5;System.out.println(decodeAtIndex(S, K));}static String decodeAtIndex(String S, int K) {long length = 0;for (char c : S.toCharArray()) {if (c >= 48 && c <= 57) {length *= c - '0';} else {++length;}}for (int i = S.length() - 1; i >= 0; i--) {char c = S.charAt(i);K %= length;if (c >= 48 && c <= 57) {length /= c - '0';} else if (K == 0) {return String.valueOf(c);} else {--length;}}return "";}}
C++
#include <bits/stdc++.h>using namespace std;string decodeAtIndex(string S, int K){long long int n = S.size();long long int len = 0;if (K == 1){if (isalpha(S[0]))return string(1, S[0]);elsereturn "";}for (long long int i = 0; i < n; i++){if (isdigit(S[i]))len = len * (S[i] - '0');elselen++;}for (long long int i = n - 1; i >= 0; i--){K %= len;if (K == 0 && isalpha(S[i]))return string(1, S[i]);else if (isdigit(S[i]))len = len / (S[i] - '0');elselen--;}return "";}int main(){string S = "ha22";int K = 5;cout << decodeAtIndex(S, K);return 0;}
No comments:
Post a Comment