簡単なアプローチは、3のシーケンスを取り、それらを。に入れることHashTable
です。3のシーケンスに遭遇するとすぐに、対応するオカレンスカウンターをインクリメントします。最後に、最も頻繁に発生する/シーケンスを返すだけHashTable
です。これは、最大発生値を持つエントリをスキャンすることで検出されます。Javaでの例:
public class Sequence {
public List<String> sequenceOfThree(List<List<String>> names){
Map<List<String>, Integer> map = new HashMap<List<String>, Integer>();
for(List<String> nameList:names){
int startIdx = 0;
int endIdx = 3;
while(endIdx <= nameList.size()){
List<String> subsequence = nameList.subList(startIdx, endIdx);
//add to map
Integer count = map.get(subsequence);
if(count == null){
count = 0;
}
map.put(subsequence, count + 1);
startIdx++;
endIdx++;
}
}
Integer max = Integer.MIN_VALUE;
List<String> result = Collections.emptyList();
for(Entry<List<String>, Integer> entries:map.entrySet()){
if(entries.getValue() > max){
max = entries.getValue();
result = entries.getKey();
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
List<List<String>> names = new ArrayList<List<String>>();
names.add(Arrays.asList(new String[]{"Ana", "John", "Maria"}));
names.add(Arrays.asList(new String[]{"Paul"}));
names.add(Arrays.asList(new String[]
{"Sharon", "Ana", "John", "Maria", "Tiffany" ,"Ted"}));
System.out.println(new Sequence().sequenceOfThree(names));
}
}