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.
1import re
2def find_valid_emails(users):
3 pattern = r'^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\.com$'
4 valid_emails = [user for user in users if re.match(pattern, user['mail'])]
5 return valid_emails
6
7# Example usage
8users = [
9 {'user_id': 1, 'name': 'Winston', 'mail': 'winston@leetcode.com'},
10 {'user_id': 2, 'name': 'Jonathan', 'mail': 'jonathanisgreat'},
11 {'user_id': 3, 'name': 'Annabelle', 'mail': 'bella-@leetcode.com'},
12 {'user_id': 4, 'name': 'Sally', 'mail': 'sally.come@leetcode.com'},
13 {'user_id': 5, 'name': 'Marwan', 'mail': 'quarz#2020@leetcode.com'},
14 {'user_id': 6, 'name': 'David', 'mail': 'david69@gmail.com'},
15 {'user_id': 7, 'name': 'Shapiro', 'mail': '.shapo@leetcode.com'}
16]
17
18valid_users = find_valid_emails(users)
19print(valid_users)
20This Python solution utilizes the 're' module to define a regular expression pattern that matches valid emails. The pattern checks if the email starts with a letter and is followed by any combination of allowed characters before the fixed domain '@leetcode.com'. The function iterates through the list of users, filters valid emails using 're.match', and returns the filtered list.
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.
1import java.util.*;
2
3
This Java solution manually parses the email to separate the prefix and domain parts. It checks if the domain matches '@leetcode.com' and validates the prefix according to rules. This approach foregoes regex for explicit parsing and logical checking.