Domanda di colloquio di Google

Write a code to find out if two string words are anagrams

Risposte di colloquio

Anonimo

12 nov 2011

boolean areAnagrams?( String s1, String s2) { int s1Length = s1.length(), s2Length = s2.length(); if(s1Length != s2Length ) return false; int[] frequencies = new int[128]; //assuming ascii. make a hash table for unicode for( int i = 0; i < frequencies.length; i++) { frequencies[ i ] = 0; } for(int i = 0; i < s1Length; i++) { frequencies[ (int)s1.charAt(i) ]++; }//now we have an int array corresponding to letter frequencies for(int i = 0; i < s2Length; i++) { frequencies[ (int)s2.charAt(i) ]--; }//now, if they are anagrams, all will be zero for(int = 0; i < s1Length; i++) { if( frequencies[ (int)s1.charAt(i) ] ) {//evaluates to true for anything but zero return false; } } return true; }

3

Anonimo

4 nov 2011

Sort the characters in the words. Compare them. Complexity : O(n log n) depending on the sort algorithm.

2

Anonimo

1 mag 2012

@rob, for ascii assumption we will require array size of 256

Anonimo

17 ott 2011

First way is to use HashMaps (quick but not memory use effective) Second is to use arrays (memory effective but slower).