-
[알고리즘] Unique Email Addresses알고리즘/배열 2021. 4. 21. 10:59
Problem
Key Point
String 클래스의 subString(), indexOf()
String str = "abcdefg"; str.subString(5); // fg str.subString(2,4) // cd (2포함O, 4포함X) String email = "abc@naver.com"; str.indexOf("@"); // 3
Code
public class UniqueEmailAddress { public int solution(String[] emails) { Set<String> emailSet = new HashSet<>(); for (String email : emails) { String localName = getLocalName(email); String domainName = getDomainName(email); emailSet.add(localName + domainName); } return emailSet.size(); } private String getDomainName(String email) { return email.substring(email.indexOf("@")); } private String getLocalName(String email) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < email.length(); i++) { char c = email.charAt(i); if(c == '.') continue; if(c == '+') break; if(c == '@') break; sb.append(c); } return sb.toString(); } public static void main(String[] args) { String[] emails = {"test.email+james@coding.com", "test.e.mail+toto.jane@coding.com", "testemail+tom@cod.ing.com"}; UniqueEmailAddress problem = new UniqueEmailAddress(); System.out.println(problem.solution(emails)); } }
'알고리즘 > 배열' 카테고리의 다른 글
[알고리즘] Maximum Subarray (0) 2021.04.21 [알고리즘] Longest Substring (0) 2021.04.21 [알고리즘] Move Zeroes (0) 2021.04.20 [알고리즘] Two Sum (0) 2021.04.20 [알고리즘] Daily temperatures (O) (0) 2021.04.20