You have all the substrings of words in this list and keep track of their substrings. The one with the maximum occurrences is the one you want. Here is an example implementation. It returns the most common substring
static String mostCommon(List<String> list) { Map<String, Integer> word2Freq = new HashMap<String, Integer>(); String maxFreqWord = null; int maxFreq = 0; for (String word : list) { for (int i = 0; i < word.length(); ++i) { String sub = word.substring(0, i + 1); Integer f = word2Freq.get(sub); if (f == null) { f = 0; } word2Freq.put(sub, f + 1); if (f + 1 > maxFreq) { if (maxFreqWord == null || maxFreqWord.length() < sub.length()) { maxFreq = f + 1; maxFreqWord = sub; } } } } return maxFreqWord; }
The above implementation may not be sufficient if you use more than one common substring. Use the card inside it.
System.out.println(mostCommon(Arrays.asList("ABC1", "ABC2", "ABC_Whatever"))); System.out.println(mostCommon(Arrays.asList("ABCDEFG1", "ABGG2", "ABC11_Whatever")));
Returns
ABC AB
source share