Pergunta de entrevista da empresa Google

Find the most frequent letters in a string.

Respostas da entrevista

Sigiloso

21 de jan. de 2012

package com.google; import java.io.ObjectInputStream.GetField; public class FrequentLettre{ public static char findFrequent(String str){ str = str.toLowerCase(); char[] chars = str.toCharArray(); int size = 'z'-'a'+1; int[] frequent = new int[size]; for (char c : chars){ Character.getNumericValue('a'); Character.getNumericValue('p'); ++frequent[c-'a']; } int max = frequent['a'-'a']; int maxInd = 0; for (int i=1; i max){ max = frequent[i]; maxInd = i; } } return (char) ('a'+maxInd); } public static void main (String[] args){ System.out.println(findFrequent("apple")); } }

Sigiloso

20 de abr. de 2012

count sort

Sigiloso

31 de mai. de 2013

Maybe store them as a hash table, keep track of the max. On every addition, if the recent added hash[letter] > hash[max], max = letter...return max If we want to return multiple letters (say like in the word "letter" where e & t have the same frequency). We can store the letters in an boolean array (which takes at most O(size of alphabet) space) and if hash[letter] = hash[max], set the array[letter] = true. Keep the same > & < rules as above but if one of them hits, set the array to false and set array[letter] = true. Return the boolean array or grab the true values and return those.