LeetCode Solutions
831. Masking Personal Information
Time: $O(1)$ Space: $O(1)$
class Solution {
public:
string maskPII(string S) {
const int atIndex = S.find('@');
if (atIndex != string::npos) {
transform(begin(S), end(S), begin(S), ::tolower);
return S.substr(0, 1) + "*****" + S.substr(atIndex - 1);
}
string s;
for (const char c : S)
if (isdigit(c))
s += c;
if (s.length() == 10)
return "***-***-" + s.substr(s.length() - 4);
return '+' + string(s.length() - 10, '*') + "-***-***-" +
s.substr(s.length() - 4);
}
};
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();
}
}
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:]