Created
September 22, 2013 23:29
-
-
Save wszdwp/6664869 to your computer and use it in GitHub Desktop.
Cracking the interview 19.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Hashtable; | |
public class Question198 | |
{ | |
public static Hashtable<String, Integer> createHashtable(String[] book) { | |
Hashtable<String, Integer> table = new Hashtable<String, Integer>(); | |
for(int i = 0; i < book.length; i++) { | |
book[i] = book[i].toLowerCase(); | |
if(book[i].trim() != "") { | |
if( !table.containsKey(book[i])) { | |
table.put(book[i], 1); | |
} | |
else{ | |
table.put(book[i], table.get(book[i]) + 1); | |
} | |
} | |
} | |
return table; | |
} | |
public static int getFrequency(Hashtable<String, Integer> table, String word) { | |
if( table == null || word == null) return -1; | |
word = word.toLowerCase(); | |
if( table.containsKey(word)) { | |
return table.get(word); | |
} | |
return 0; | |
} | |
public static void main(String[] args) { | |
String[] book1 = {"This", "is", "a", "is", "case",}; | |
Hashtable<String, Integer> test1 = createHashtable(book1); | |
String word1 = "is"; | |
String word2 = "a"; | |
String word3 = "case"; | |
System.out.println("Expected(2): " + getFrequency(test1, word1)); | |
System.out.println("Expected(1): " + getFrequency(test1, word2)); | |
System.out.println("Expected(1): " + getFrequency(test1, word3)); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment