LeetCode-in-Java

831. Masking Personal Information

Medium

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:

To mask an email:

Phone number:

A phone number is formatted as follows:

To mask a phone number:

Example 1:

Input: s = “LeetCode@LeetCode.com”

Output: “l*****e@leetcode.com”

Explanation: s is an email address.

The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.

Example 2:

Input: s = “AB@qq.com”

Output: “a*****b@qq.com”

Explanation: s is an email address.

The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.

Note that even though “ab” is 2 characters, it still must have 5 asterisks in the middle.

Example 3:

Input: s = “1(234)567-890”

Output: “***-***-7890”

Explanation: s is a phone number.

There are 10 digits, so the local number is 10 digits and the country code is 0 digits.

Thus, the resulting masked number is “***-***-7890”.

Constraints:

Solution

public class Solution {
    public String maskPII(String s) {
        StringBuilder masked = new StringBuilder();
        if (Character.isAlphabetic(s.charAt(0))) {
            int locationOfAtSymbol = s.indexOf("@") - 1;
            masked.append(s.charAt(0)).append("*****").append(s.substring(locationOfAtSymbol));
            return masked.toString().toLowerCase();
        } else {
            StringBuilder allDigits = new StringBuilder();
            int pointer = -1;
            while (++pointer < s.length()) {
                if (Character.isDigit(s.charAt(pointer))) {
                    allDigits.append(s.charAt(pointer));
                }
            }
            int numDigits = allDigits.length();
            if (numDigits == 11) {
                masked.append("+*-");
            } else if (numDigits == 12) {
                masked.append("+**-");
            } else if (numDigits == 13) {
                masked.append("+***-");
            }
            masked.append("***-***-").append(allDigits.substring(numDigits - 4));
            return masked.toString();
        }
    }
}