Monday, March 16, 2020

LeetCode 1309. Decrypt String from Alphabet to Integer Mapping

Question: https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/
Easy Question Again. Since the indicator for a change in character mapping comes from the end with "#", we will need to iterate from behind. One thing to be careful is with the indexing when getting the substring from the input string. First of all, the number of characters extracted from any index pairs such as s[i, i+k] will yield back i+k-i = k characters. So s[i-2:i] gives back 2 characters, exactly what we want. Secondly, s[i-2:i] will include s[i-2] character and exclude s[i]. Just try to avoid these common mistakes, then we are good to go!


class Solution(object):
    def freqAlphabets(self, s):
        """
        :type s: str
        :rtype: str
        """
        ans = []
        char_map = {}
        atoi = ord("a")
        for i in range(1, 27):
            curchar = chr(atoi+i-1)
            char_map["{}".format(i)] = curchar
            
        n = len(s)
        i = n-1
        while i >= 0:
            if s[i] == "#":
                print(i-2, i)
                ans.append(char_map[s[i-2:i]])
                i -= 3
            else:
                ans.append(char_map[s[i]])
                i -= 1
        return "".join(reversed(ans))

No comments:

Post a Comment