Sponsored
Sponsored
In this approach, we use regular expressions to check for valid emails. The regular expression will ensure that the email format adheres to the specified rules: the prefix starts with a letter and consists only of permitted characters, followed by '@leetcode.com'. This method efficiently checks the constraints by leveraging regular expressions, which are well-suited for pattern matching tasks.
The time complexity of this solution is O(n), where n is the number of users, as each email is scanned once. The space complexity is O(n) as we store all valid users in a list.
1function findValidEmails
A JavaScript solution using the 'RegExp' object to verify if each email matches the specified pattern. It uses a similar filtering approach as those in other languages.
This approach involves manually parsing the email to check the prefix and domain components. We split the email at the '@' character and validate both parts separately. This is an alternative to regex that provides a more step-by-step checking method.
The time complexity is O(n * m), where n is the number of users and m is the length of the largest email string due to manual character checking. The space complexity is O(n) for the result list.
1def find_valid_emails(users):
2 def is_valid_email(mail):
3 if '@leetcode.com' not in mail:
4 return False
5 prefix, domain = mail.split('@', 1)
6 if domain != 'leetcode.com':
7 return False
8 if not prefix or not prefix[0].isalpha():
9 return False
10 for char in prefix:
11 if not (char.isalnum() or char in '._-'):
12 return False
13 return True
14
15 valid_emails = [user for user in users if is_valid_email(user['mail'])]
16 return valid_emails
17
18# Example usage
19users = [
20 {'user_id': 1, 'name': 'Winston', 'mail': 'winston@leetcode.com'},
21 {'user_id': 2, 'name': 'Jonathan', 'mail': 'jonathanisgreat'},
22 {'user_id': 3, 'name': 'Annabelle', 'mail': 'bella-@leetcode.com'},
23 {'user_id': 4, 'name': 'Sally', 'mail': 'sally.come@leetcode.com'},
24 {'user_id': 5, 'name': 'Marwan', 'mail': 'quarz#2020@leetcode.com'},
25 {'user_id': 6, 'name': 'David', 'mail': 'david69@gmail.com'},
26 {'user_id': 7, 'name': 'Shapiro', 'mail': '.shapo@leetcode.com'}
27]
28
29valid_users = find_valid_emails(users)
30print(valid_users)
31
This Python function manually splits the email at '@', checks if the domain is 'leetcode.com', and ensures that the prefix starts with a letter and contains only allowed characters. This approach is more granular and does not use regex, making it useful for understanding email validation through conditional checks.