Skip to content

1309. Decrypt String from Alphabet to Integer Mapping 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  string freqAlphabets(string s) {
    string ans;

    for (int i = 0; i < s.length();) {
      if (i + 2 < s.length() && s[i + 2] == '#') {
        ans += stoi(s.substr(i, 2)) + 'a' - 1;
        i += 3;
      } else {
        ans += (s[i] - '0') + 'a' - 1;
        i += 1;
      }
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public String freqAlphabets(String s) {
    String ans = "";

    for (int i = 0; i < s.length();) {
      if (i + 2 < s.length() && s.charAt(i + 2) == '#') {
        ans += (char) (Integer.valueOf(s.substring(i, i + 2)) + 'a' - 1);
        i += 3;
      } else {
        ans += (char) ((s.charAt(i) - '0') + 'a' - 1);
        i += 1;
      }
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def freqAlphabets(self, s: str) -> str:
    ans = ''
    i = 0

    while i < len(s):
      if i + 2 < len(s) and s[i + 2] == '#':
        ans += chr(int(s[i:i + 2]) + ord('a') - 1)
        i += 3
      else:
        ans += chr(int(s[i]) + ord('a') - 1)
        i += 1

    return ans