Leetcode 831. Masking Personal Information
You are given a string S
which can be an email address or a phone number. Your task is to mask the personal information following these rules:
1. Email:
first_character*****last_character@domain
.2. Phone Number:
***-***-XXXX
, where XXXX
are the last four digits.+**
.Given the string S
, you need to return the masked version of either the email or the phone number.
S
be assumed to be well-formatted?1. Recognize Email or Phone Number:
2. Masking the Email:
3. Masking the Phone Number:
4. Regex patterns and standard library methods will aid in recognizing and transforming the string accordingly.
public class Solution {
public String maskPII(String S) {
if (S.contains("@")) {
return maskEmail(S);
} else {
return maskPhone(S);
}
}
private String maskEmail(String email) {
email = email.toLowerCase();
String[] parts = email.split("@");
String namePart = parts[0];
String domainPart = parts[1];
return namePart.charAt(0) + "*****" + namePart.charAt(namePart.length() - 1) + "@" + domainPart;
}
private String maskPhone(String phone) {
StringBuilder digits = new StringBuilder();
for (char c : phone.toCharArray()) {
if (Character.isDigit(c)) {
digits.append(c);
}
}
int len = digits.length();
String localNumber = "***-***-" + digits.substring(len - 4);
if (len == 10) {
return localNumber;
} else {
StringBuilder maskedPhone = new StringBuilder("+");
for (int i = 0; i < len - 10; i++) {
maskedPhone.append('*');
}
maskedPhone.append('-').append(localNumber);
return maskedPhone.toString();
}
}
// Test the functionality
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.maskPII("LeetCode@LeetCode.com")); // Expected: "l*****e@leetcode.com"
System.out.println(sol.maskPII("AB@qq.com")); // Expected: "a*****b@qq.com"
System.out.println(sol.maskPII("1(234)567-890")); // Expected: "***-***-7890"
System.out.println(sol.maskPII("+123-456-789-0123")); // Expected: "+**-***-***-0123"
}
}
n
is the length of the input string.n
is the length of the input string.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?