/** * Helper function for contains that takes in a String s and a LetterNode letter and verifies that * the first letter of s matches the LetterNode letter. If this does not hold; returns false. * * @param s is the prefix being checked if it is in the dictionary * @param letter is compared to the first letter of s to see if s is in the dictionary */ public boolean containsHelper(String s, LetterNode w) { // If w's letter is equal to the first letter of s if (w.toString().equals(s.substring(0, 1))) { // If s has one letter and the corresponding TreeNode // completesFullWord, then the word is in the Trie. if (s.length() == 1) { if (w.completesFullWord) { return true; } else { return false; } } else { LetterNode nextPossible = w.getNextLetter(s.substring(1, 2)); // If child LetterNode corresponding to the next letter does not exist if (nextPossible == null) { return false; } else { return containsHelper(s.substring(1), nextPossible); } } } return false; }
/* If Trie has child corresponding to letter, then return the child. * Else create the child and return it. * */ public LetterNode getFirstLetter(String letter) { for (int x = 0; x < myChildren.size(); x++) { LetterNode current = myChildren.get(x); if (current.toString().equals(letter)) { return current; } } LetterNode newLetter = new LetterNode(letter, null); myChildren.add(newLetter); return newLetter; }
/** * Helper function for containsPrefix that takes in a String s and a LetterNode letter and * verifies that the first letter of s matches the LetterNode letter. If this does not hold; * returns false. * * @param s is the prefix being checked if it is in the dictionary * @param letter is compared to the first letter of s to see if s is in the dictionary */ private boolean containsPrefixHelper(String s, LetterNode letter) { // If w's letter is equal to the first letter of s if (letter.toString().equals(s.substring(0, 1))) { // If s has one letter, then the prefix is in the Trie. if (s.length() == 1) { return true; } else { LetterNode nextPossible = letter.getNextLetter(s.substring(1, 2)); // If child LetterNode corresponding to the next letter does not exist if (nextPossible == null) { return false; } else { return containsPrefixHelper(s.substring(1), nextPossible); } } } return false; }
/** * If the prefix is in the lexicon, returns true. * * @param s The word to search for. * @return True if the lexicon contains s. */ public boolean containsPrefix(String s) { // Check for empty string if (s == "") { return false; } // Indicates if the Trie has a child corresponding to the first letter of s. // By default hasFirstLetter's value is false. boolean hasFirstLetter = false; for (int x = 0; x < myDictionary.myChildren.size(); x++) { LetterNode current = myDictionary.myChildren.get(x); if (current.toString().equals(s.substring(0, 1))) { hasFirstLetter = true; } } return hasFirstLetter && containsPrefixHelper(s, myDictionary.getFirstLetter(s.substring(0, 1))); }