Pergunta de entrevista da empresa Amazon

Given two different strings, find the common characters between the two. For example if string A is "hello" and string B is "elbow" the common characters would be ['e', 'l', 'o']. Give a method that returns unique or duplicate entries.

Respostas da entrevista

Sigiloso

10 de jan. de 2014

Using python sets, create the two sets of characters, then return the intersection. This will return the set of characters that are in both strings. from sets import Set def duplicateChars(s1, s2): s1set = set() s2set = set() for c in s1: s1set.add(c) for c in s2: s2set.add(c) return s1set.intersection(s2set) print duplicateChars("string", "ring")

1

Sigiloso

11 de jan. de 2014

Solution in Java: public class StringIntersection { String str1 = "hello"; String str2 = "elbow"; public Set findIntersection() { String[] arr1 = str1.split(""); String[] arr2 = str2.split(""); List list = Arrays.asList(arr1); Set set = new LinkedHashSet(Arrays.asList(arr1)); set.retainAll(Arrays.asList(arr2)); set.remove(""); return set; // returns [e, l, o] } }

1