Masking Personal Information

To mask the personal information according to the given rules, we can differentiate between email addresses and phone numbers based on the characters in the given string s. We’ll write separate functions for masking emails and phone numbers and apply them accordingly.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def maskPII(self, s: str) -> str:
        if '@' in s:
            return self.maskEmail(s)
        else:
            return self.maskPhone(s)

    def maskEmail(self, s: str) -> str:
        parts = s.split('@')
        return parts[0][0].lower() + "*****" + parts[0][-1].lower() + "@" + parts[1].lower()

    def maskPhone(self, s: str) -> str:
        digits = [char for char in s if char.isdigit()]
        local_number = "***-***-" + "".join(digits[-4:])
        if len(digits) == 10:
            return local_number
        else:
            country_code_stars = '*' * (len(digits) - 10)
            return "+" + country_code_stars + "-" + local_number

Explanation:

  • If s contains an ‘@’, we consider it an email address and call the maskEmail function. Otherwise, we call the maskPhone function.
  • maskEmail splits the email into two parts, the name and the domain, then constructs the masked email as described in the problem.
  • maskPhone filters out the digits from the phone number, constructs the local number, and then adds the country code, if present, using the given formatting rules.

The code ensures that the masking is performed according to the constraints, following the given examples.