We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My solution using binomial coefficient (refer to combination without repetitions).
publicstaticintsherlockAndAnagrams(Strings){// Write your code hereHashMap<String,Integer>map=newHashMap<>();char[]chars=s.toCharArray();for(inti=0;i<chars.length;i++){addItOrSum1(map,String.valueOf(chars[i]));List<Character>word=newArrayList<>();word.add(chars[i]);for(intj=i+1;j<chars.length;j++){word.add(chars[j]);Stringcollect=word.stream().sorted().map(Object::toString).collect(Collectors.joining());addItOrSum1(map,collect);}}returnmap.values().stream().map(x->x>2?binomialCoefficient(x,2):x).reduce(Integer::sum).orElse(0);}publicstaticvoidaddItOrSum1(Map<String,Integer>map,Strings){Integervalue=map.getOrDefault(s,-1);if(value==1){++value;}map.put(s,++value);}privatestaticintbinomialCoefficient(intn,intk){if(k>n-k)k=n-k;longbinom=1;for(inti=1;i<=k;i++)binom=binom*(n+1-i)/i;return(int)binom;}
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
My solution using binomial coefficient (refer to combination without repetitions).