StringBuilder VI

Another problem where using String leads to a time limit exceeded, but StringBuilder (just for the token processing) does the trick. Just some calculation is needed for the characters rotation. Code is down below, cheers, ACC.

Decrypt the Message - LeetCode

You are given a string s representing an encrypted message consisting of one or more tokens.

Each token consists of lowercase English letters, followed by '#' and an integer representing its encryption key. The tokens are separated by single spaces.

To decrypt a token, shift each letter backward by the number of positions specified by its key. The alphabet wraps around, so shifting 'a' backward by one position produces 'z'.

Return the decrypted message, with the keys removed and the decrypted words in their original order, separated by single spaces.

 

Example 1:

Input: s = "abc#1"

Output: "zab"

Explanation:

  • The token "abc#1" has a key of 1, so each letter is shifted backward by one position.
  • The letter 'a' wraps around to 'z', while 'b' and 'c' become 'a' and 'b', respectively.
  • Thus, the decrypted message is "zab".

Example 2:

Input: s = "az#2 bcd#27"

Output: "yx abc"

Explanation:

  • The token "az#2" has a key of 2, so its letters are shifted backward by two positions, becoming "yx".
  • The token "bcd#27" has a key of 27, which is equivalent to shifting backward by one position. Its letters become "abc".
  • Thus, the decrypted message is "yx abc".

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of lowercase English letters, '#', digits, and spaces.
  • Tokens are separated by exactly one space, with no leading or trailing spaces.
  • Each token contains one or more lowercase English letters, followed by '#' and an integer in the range [1, 109] without leading zeros.


public class Solution {
    public string DecryptMessage(string s)
    {
        string[] parts = s.Split(" ");
        string retVal = "";

        foreach (string part in parts)
        {
            retVal += DecryptToken(part) + " ";
        }

        return retVal.Trim();
    }

    private string DecryptToken(string token)
    {
        string[] parts = token.Split("#");
        string t = parts[0];
        int rotation = (Int32.Parse(parts[1])) % 26;

        StringBuilder sb = new StringBuilder();

        foreach (char c in t)
        {
            int prev = (int)c - rotation;
            if (prev < (int)'a') prev += 26;
            sb.Append((char)prev);
        }

        return sb.ToString();
    }
}

Comments

Popular posts from this blog

Standard Priority Queue IX: Vowels Frequency

Binary Search to Find Next Greater Element V

Simulation: Build Generations