831. Masking Personal Information
Explanation:
- We need to mask the personal information string based on whether it represents an email address or a phone number.
- For email addresses, we need to convert the name and domain to lowercase and replace the middle characters of the name with asterisks.
- For phone numbers, we need to remove separation characters and mask the number accordingly.
:
class Solution {
public String maskPII(String s) {
if (s.contains("@")) {
return maskEmail(s);
} else {
return maskPhoneNumber(s);
}
}
private String maskEmail(String email) {
int atIndex = email.indexOf('@');
String name = email.substring(0, atIndex).toLowerCase();
String domain = email.substring(atIndex).toLowerCase();
return name.charAt(0) + "*****" + name.charAt(name.length() - 1) + domain;
}
private String maskPhoneNumber(String phone) {
String digits = phone.replaceAll("\\D", "");
int localLength = digits.length() - 10;
String masked = "***-***-" + digits.substring(digits.length() - 4);
if (localLength > 0) {
String country = "+";
for (int i = 0; i < localLength; i++) {
country += "*";
}
return country + "-" + masked;
}
return masked;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.