Decoded String at Index

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 written d-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 Sint 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 Sint K)
{
    long long int n = S.size();
    long long int len = 0;
    if (K == 1)
    {
        if (isalpha(S[0]))
            return string(1S[0]);
        else
            return "";
    }
    for (long long int i = 0i < ni++)
    {
        if (isdigit(S[i]))
            len = len * (S[i] - '0');
        else
            len++;
    }
    for (long long int i = n - 1i >= 0i--)
    {
        K %= len;
        if (K == 0 && isalpha(S[i]))
            return string(1S[i]);
        else if (isdigit(S[i]))
            len = len / (S[i] - '0');
        else
            len--;
    }
    return "";
}

int main()
{
    string S = "ha22";
    int K = 5;
    cout << decodeAtIndex(SK);
    return 0;
}


No comments:

Post a Comment