很直接的题目,按照题目的说法实现即可。线性时间复杂度,代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string maskPII(string S) { | |
if(isalpha(S[0]))return maskEmail(S); | |
else return maskPhone(S); | |
} | |
private: | |
string maskEmail(string s) | |
{ | |
int len = s.size(); | |
bool firstName = true; | |
string res; | |
for(int i = 0; i < len; ++i) | |
{ | |
if(s[i] == '@') | |
{ | |
firstName = false; | |
res += "*****"; | |
res += tolower(s[i - 1]); | |
res += s[i]; | |
} | |
else | |
{ | |
if(!i)res += tolower(s[i]); | |
else if(!firstName)res += tolower(s[i]); | |
} | |
} | |
return res; | |
} | |
string maskPhone(string s) | |
{ | |
int len = s.size(); | |
string res; | |
for(int i = len - 1; i >= 0; --i) | |
{ | |
if(isdigit(s[i])) | |
{ | |
int n = res.size(); | |
if(n == 4 || n == 8 || n == 12)res = "-" + res; | |
res = n < 4? string(1, s[i]) + res: "*" + res; | |
} | |
} | |
return res.size() > 12? "+" + res: res; | |
} | |
}; |
No comments:
Post a Comment