Leetcode 831 Masking Personal Information

这是题目描述

这是示例

思路:
先判断到底是email还是phonenumber,根据情况依次判断
email只取@符号前面的字符串的首末两个字符,其余不变(当然要先把所有的变成小写)
phone就判断数字有多少个,超过10就多一个+号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def maskPII(S):
# 定义一个flag,为1的时候代表是email,为0的时候代表是phonenumber
# 初始化为1,即默认是email,通过开头是否是数字或符号来判断是否改变
flag = 1
if S[0] in '()0123456789+-': flag = 0

const_str = '***-***-'
if flag == 0: # means S is phonenumber
cnt = 0 # 记录S中数字的长度
rec = '' # 记录S中最后四位数字
for e in range(len(S)-1,-1,-1):
if S[e] in '1234567890':
cnt += 1
if cnt <= 4: rec += S[e]
if cnt == 10: return const_str + rec[::-1]
else: return '+' + '*'*(cnt-10) + '-' + const_str + rec[::-1]

if flag == 1: # means S is email address
S = S.lower()
l,r = S.split('@')
return l[0] + '*****' + l[-1] + '@' + r

"difficulty: midium
66 / 66 test cases passed.
Runtime: 39 ms"