Problem

Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.

  • For example, in "[email protected]""alice" is the local name, and "leetcode.com" is the domain name.

If you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.

If you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.

It is possible to use both of these rules at the same time.

Given an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.

Examples

Example 1:

Input:
emails = ["[email protected]","[email protected]","[email protected]"]
Output:
 2
Explanation: "[email protected]" and "[email protected]" actually receive mails.

Example 2:

Input:
emails = ["[email protected]","[email protected]","[email protected]"]
Output:
 3

Solution

Method 1 - Iterating Chars and Using Builtins

Code

Java
public int numUniqueEmails(String[] emails) {
   Set<String> uniqueEmails = new HashSet<>();

	for (String email : emails) {
		String[] emailParts = email.split("@");
		String local = emailParts[0], domain = emailParts[1];

		local = local.split("+")[0];
		local = local.replace("\.", '');
		uniqueEmails.add(local+"@"+domain);
	}

	return uniqueEmails.size();
}

Method 2 - Iterating Chars in String without Builtins

Code

Java
public int numUniqueEmails(String[] emails) {
   Set<String> uniqueEmails = new HashSet<>();

	for (String email : emails) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < email.length(); i++) {
			char c = email.charAt(i);
			if (c == '.') {
				continue;
			} else if (c == '+') {

				// skip all the characters
				while (email.charAt(i) != '@') {
					i++;
				}

				i--;// add the skipped alpha back to email

			} else if (c == '@') {
				sb.append(email.substring(i)); // include rest of string and exit loop
				break;
			} else {
				sb.append(c);
			}

		}
		uniqueEmails.add(sb.toString());
	}

	return uniqueEmails.size();
}