TagMatches.java

package personal.interview.realInterviewQuestions; import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; /** * Created by ksoundararaj on 2/20/17. */ public class GrandRounds { /* * Complete the function below. */ Map<String, Set<String>> tagNameMap = new HashMap(); private List<String> findMatches(String[][] nameTags, String tag1, String tag2) { if (nameTags == null || nameTags.length < 2) { return new ArrayList<String>(); } for (int i = 1; i<nameTags.length; i++) { String[] row = nameTags[i]; // Assumption : Row is valid String name = row[0]; String tags = row[1]; String[] splitTags = tags.split(","); for (String tag: splitTags) { tag = tag.trim(); if (!tagNameMap.containsKey(tag)) { tagNameMap.put(tag, new HashSet<String>()); } tagNameMap.get(tag).add(name); } } Set<String> s1 = tagNameMap.get(tag1); Set<String> s2 = tagNameMap.get(tag2); if (s1.size() < s2.size()) { Set<String> tmp = s1; s1 = s2; s2 = s1; } List<String> retVal = new ArrayList<String>(); for (String s : s1) if (s2.contains(s)) retVal.add(s); return retVal; } public static void main(String[] args) throws IOException{ String[][] nameTags = { { "name", "tags" }, { "Bob", "hungry,engineer,male"}, { "Mary", "hungry,productmanager,female,likes_burritos"}, { "Sarah", "hungry, engineer,female,likes_pizza" }, { "Joe", "thirsty"}, { "Tim", "hungry"}, { "Maggie", "hungry,thirsty,engineer,likes_pizza"} }; List<String> retVal = new GrandRounds().findMatches(nameTags, "thirsty", "female"); for (String s : retVal) { System.out.print(s + "\t"); } } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.