Similar Problems
Similar Problems not available
Masking Personal Information - Leetcode Solution
Companies:
LeetCode: Masking Personal Information Leetcode Solution
Difficulty: Medium
Topics: string
Masking Personal Information problem on LeetCode is described as follows:
You are given a string S representing a personal information, such as an email address or a phone number.
We would like to mask this personal information according to the following rules:
- Email address:
We define a name to be a string of length ≥ 2 consisting of only lowercase letters a-z or uppercase letters A-Z.
An email address consists of two parts: local name and domain name separated by the '@' sign.
- The local name can contain any character, except for the '@' sign.
- The domain name can contain any character, except for the '.' sign.
To mask an email address:
a. Convert all characters in the local name to lowercase.
b. Replace all characters in the domain name with '*' (asterisk) characters, except for the first and last character.
Example 1: Input: "JohnDoe@example.com" Output: "j*****e@example.com" Explanation: All letters in the local name are converted to lowercase, and the domain name is masked.
- Phone number:
A phone number consists of a string of digits, possibly preceded by a '+' sign and/or followed by a space or '-'.
To mask a phone number:
a. Remove all non-digits characters.
b. If the phone number has 10 or more digits, mask all but the last four digits. Otherwise, do not mask any digits.
Example 2: Input: "1(234)567-890" Output: "--7890" Explanation: All non-digits characters are removed, and the last four digits are not masked because the phone number has less than ten digits.
Given a personal information string S, your task is to return the masked personal information.
To solve this problem, we need to follow the given rules to mask the personal information string. We can do this by using conditional statements and string functions in Python.
Here is the solution in Python:
class Solution: def maskPII(self, S: str) -> str: if '@' in S: # Masking email address local, domain = S.split('@') # Convert local to lowercase local = local.lower() # Mask domain domain = '' * (len(domain)-2) + domain[-2:] return local + '@' + domain else: # Masking phone number digits = [c for c in S if c.isdigit()] if len(digits) == 10: return '--' + ''.join(digits[-4:]) else: return '+' + ''(len(digits)-10) + '--*-' + ''.join(digits[-4:])
Test Cases:
assert Solution().maskPII("JohnDoe@example.com") == "je@example.com" assert Solution().maskPII("1(234)567-890") == "--7890" assert Solution().maskPII("+1(234)567-890") == "+---7890" assert Solution().maskPII("+(123)456-7890") == "+--7890" assert Solution().maskPII("A@leetcode.com") == "a*****e@leetcode.com"
Masking Personal Information Solution Code
1