Skip to content

831. Masking Personal Information 👎

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  string maskPII(string s) {
    const int atIndex = s.find('@');
    if (atIndex != string::npos) {
      ranges::transform(s, s.begin(), ::tolower);
      return s.substr(0, 1) + "*****" + s.substr(atIndex - 1);
    }

    string ans;
    for (const char c : s)
      if (isdigit(c))
        ans += c;

    if (ans.length() == 10)
      return "***-***-" + ans.substr(ans.length() - 4);
    return '+' + string(ans.length() - 10, '*') + "-***-***-" +
           ans.substr(ans.length() - 4);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String maskPII(String s) {
    final int atIndex = s.indexOf('@');
    if (atIndex > 0) {
      s = s.toLowerCase();
      return s.charAt(0) + "*****" + s.substring(atIndex - 1);
    }

    StringBuilder sb = new StringBuilder();
    for (final char c : s.toCharArray())
      if (Character.isDigit(c))
        sb.append(c);

    if (sb.length() == 10)
      return "***-***-" + sb.substring(sb.length() - 4).toString();
    return '+' + "*".repeat(sb.length() - 10) + "-***-***-" +
        sb.substring(sb.length() - 4).toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maskPII(self, s: str) -> str:
    atIndex = s.find('@')
    if atIndex != -1:
      s = s.lower()
      return s[0] + '*' * 5 + s[atIndex - 1:]

    ans = ''.join(c for c in s if c.isdigit())

    if len(ans) == 10:
      return '***-***-' + ans[-4:]
    return '+' + '*' * (len(ans) - 10) + '-***-***-' + ans[-4:]