class Solution {
public int numUniqueEmails(String[] emails) {
List finalEmails = new ArrayList();
for(String email : emails) {
char[] chs = email.toCharArray();
boolean afterPlussignAndBeforeAt = false;
boolean beforeAt = true;
StringBuffer sb = new StringBuffer();
for(char ch : chs) {
if(afterPlussignAndBeforeAt && ch != '@')
continue;
if(ch == '@') {
afterPlussignAndBeforeAt = false;
beforeAt = false;
}
if(ch == '+')
afterPlussignAndBeforeAt = true;
if(!afterPlussignAndBeforeAt) {
if(ch == '.' && beforeAt)
continue;
sb.append(ch);
}
}
if(!finalEmails.contains(sb.toString())) {
finalEmails.add(sb.toString());
}
}
return finalEmails.size();
}
}
注:也可以使用split方法,将@前后两部分分解,分别处理。
public int numUniqueEmails(String[] emails) { Set<String> normalized = new HashSet<>(); // used to save simplified email address, cost O(n) sapce. for (String email : emails) { String[] parts = email.split("@"); // split into local and domain parts. String[] local = parts[0].split("\\+"); // split local by '+'. normalized.add(local[0].replace(".", "") + "@" + parts[1]); // remove all '.', and concatenate '@' and domain. } return normalized.size(); }