[LeetCode] Masking Personal Information

831. Masking Personal Information

You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.

Email address:

An email address is:

  • A name consisting of uppercase and lowercase English letters, followed by
  • The ‘@’ symbol, followed by
  • The domain consisting of uppercase and lowercase English letters with a dot ‘.’ somewhere in the middle (not the first or last character).

To mask an email:

  • The uppercase letters in the name and domain must be converted to lowercase letters.
  • The middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks “*“.

Phone number:

A phone number is formatted as follows:

  • The phone number contains 10-13 digits.
  • The last 10 digits make up the local number.
  • The remaining 0-3 digits, in the beginning, make up the country code.
  • Separation characters from the set {‘+’, ‘-‘, ‘(‘, ‘)’, ‘ ‘} separate the above digits in some way.

To mask a phone number:

  • Remove all separation characters.
  • The masked phone number should have the form:
  • "***-***-XXXX" if the country code has 0 digits.
  • "+*-***-***-XXXX" if the country code has 1 digit.
  • "+**-***-***-XXXX" if the country code has 2 digits.
  • "+***-***-***-XXXX" if the country code has 3 digits.
  • “XXXX” is the last 4 digits of the local number.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
string email(string s) {
string res = "";
for(int i = 0; i < s.length(); i++) {
if(isalpha(s[i])) s[i] = tolower(s[i]);
}
auto pos = s.find('@');
res = string(1,s[0]) + "*****" + s.substr(pos-1);
return res;
}
string phone(string s) {
int count = 0;
for(int i = 0; i < s.length(); i++) {
if(isdigit(s[i])) count++;
}
string res = "";
for(int i = s.length() - 1; i >= 0 and res.length() < 4; i--) {
if(isdigit(s[i]))
res.push_back(s[i]);
}
reverse(begin(res),end(res));
if(count == 10) return "***-***-" + res;
if(count == 11) return "+*-***-***-" + res;
if(count == 12) return "+**-***-***-" + res;
return "+***-***-***-" + res;
}
public:
string maskPII(string s) {
return s.find('@') != string::npos ? email(s) : phone(s);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/26/PS/LeetCode/masking-personal-information/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.