Problem
Write a program to find the longest word made of other words.Solution
EXAMPLE
Input: test, tester, testertest, testing, testingtester
Output: testingtester
- This problem can be easily solved using a "Trie data structure"
- First I sort the strings in descending order "Lengthwise", so longest string comes first.
- Start with the first string and loop over sorted strings
- Check if it can be made of other words by dividing strings into all possible combinations and doing same thing for each splits. So, whenever we find the word in the larger string, we delete the shorter word from the bigger word.
- Retrun true if it is made of other strings and Save that string onto an array list.
- Return the top string because that would be the longest string.
- The size of array list will give you the total number of words that can be made of other words.
public static class LengthComparator implements Comparator<String> { public int compare(String o1, String o2) { if (o1.length() < o2.length()) return 1; else if (o1.length() > o2.length()) return -1; else return 0; } } public static String longestWordMadeOfOtherWords(String[] words) { Arrays.sort(words, new LengthComparator()); for (String word : words) { String backup = new String(word); for (String otherWord : words) { if (!otherWord.equals(backup) && word.contains(otherWord)) { word = word.replace(otherWord, ""); } } if (word.length() == 0) return backup; } return null; }
Thanks.
References
0 comments:
Post a Comment