Leetcode 831. Masking Personal Information
You are given a string S
that represents personal information. The string can be in one of two formats: an email address or a phone number. You need to mask this personal information in the following way:
Examples:
Constraints:
S
contains ‘@’, it’s an email.#include <iostream>
#include <string>
#include <cctype>
using namespace std;
class Solution {
public:
string maskPII(string S) {
// Check if the string is an email or phone number
if (S.find('@') != string::npos) {
return maskEmail(S);
} else {
return maskPhone(S);
}
}
private:
string maskEmail(const string& email) {
int atPos = email.find('@');
string local = email.substr(0, atPos);
string domain = email.substr(atPos);
string maskedEmail = local[0] + string(5, '*') + local.back() + domain;
return maskedEmail;
}
string maskPhone(const string& phone) {
string digits;
// Extract only digits from the phone number
for (char c : phone) {
if (isdigit(c)) {
digits += c;
}
}
// The last 4 digits will remain
string last4 = digits.substr(digits.size() - 4);
// Depending on the length of digits, determine country code and masking
string maskedPhone;
int n = digits.size();
if (n == 10) {
maskedPhone = "***-***-" + last4;
} else if (n > 10) {
string countryCode = "+" + string(n - 10, '*') + "-";
maskedPhone = countryCode + "***-***-" + last4;
}
return maskedPhone;
}
};
// Example Usage
int main() {
Solution solution;
cout << solution.maskPII("le@leetcode.com") << endl; // Output: "l*****e@leetcode.com"
cout << solution.maskPII("1(234)567-890") << endl; // Output: "***-***-7890"
cout << solution.maskPII("+86-(10)12345678") << endl; // Output: "+86-***-***-5678"
return 0;
}
O(n)
, where n
is the length of the email string. This is dominated by the substring and reconstruction operations.O(n)
, where n
is the length of the phone string. This is dominated by the digit extraction process and the string reconstruction.By organizing the problem and solution in this structured manner, it becomes easier to understand and implement.
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?