给你一条个人信息字符串 s ,可能表示一个 邮箱地址 ,也可能表示一串 电话号码 。
题目链接:https://leetcode.cn/problems/masking-personal-information
题目链接:https://leetcode.cn/problems/masking-personal-information
# 解题思路
直接按题意模拟,分别处理电话号码和邮箱即可。
# 两种字符串拼接比较
- 使用 String.format ()
class Solution { | |
public String maskPII(String s) { | |
int at = s.indexOf('@'); | |
if (at != -1) { | |
// 是邮箱 | |
if (at > 0) { | |
char first = Character.toLowerCase(s.charAt(0)); | |
char last = Character.toLowerCase(s.charAt(at - 1)); | |
String domain = s.substring(at + 1).toLowerCase(); | |
return String.format("%c*****%c@%s", first, last, domain); | |
} else { | |
return ""; | |
} | |
} else { | |
// 是电话号码 | |
char[] chs = s.toCharArray(); | |
int k = 0; | |
for (int i = 0; i < chs.length; ++i) { | |
if (chs[i] >= '0' && chs[i] <= '9') { | |
chs[k++] = chs[i]; | |
} | |
} | |
if (k < 10) return ""; | |
String ph = new String(chs, k - 4, 4); | |
if (k == 10) { | |
return String.format("***-***-%s", ph); | |
} else { | |
StringBuilder sb = new StringBuilder(); | |
while (k > 10) { | |
sb.append('*'); | |
--k; | |
} | |
return String.format("+%s-***-***-%s", sb.toString(), ph); | |
} | |
} | |
} | |
} |
- 使用 StringBuilder
class Solution { | |
public String maskPII(String s) { | |
int at = s.indexOf('@'); | |
if (at != -1) { | |
// 是邮箱 | |
if (at > 0) { | |
StringBuilder ret = new StringBuilder(); | |
ret.append(Character.toLowerCase(s.charAt(0))) | |
.append("*****") | |
.append(Character.toLowerCase(s.charAt(at - 1))) | |
.append(s.substring(at).toLowerCase()); | |
return ret.toString(); | |
} else { | |
return ""; | |
} | |
} else { | |
// 是电话号码 | |
char[] chs = s.toCharArray(); | |
int k = 0; | |
for (int i = 0; i < chs.length; ++i) { | |
if (chs[i] >= '0' && chs[i] <= '9') { | |
chs[k++] = chs[i]; | |
} | |
} | |
if (k < 10) return ""; | |
StringBuilder sb = new StringBuilder(); | |
String ph = new String(chs, k - 4, 4); | |
if (k == 10) { | |
sb.append("***-***-").append(ph); | |
} else { | |
sb.append('+'); | |
while (k > 10) { | |
sb.append('*'); | |
--k; | |
} | |
sb.append("-***-***-").append(ph); | |
} | |
return sb.toString(); | |
} | |
} | |
} |