I have been given this below problem in school, I have solved as per my understanding and solution is as below. Can someone please help me to give a better solution for the same.
Question:
Produce a software application that creates a filtered merging of two case-insensitive sorted lists. The first input list is designated as the Source list and the other as the Prefixes list. The application will produce a merged list containing items that come from the Source and Prefixes lists using the following algorithm:
An item X is in the merged list if and only if one of the following is true:
a) X is from the Source list and there is an item Y in the Prefixes list that is a case-insensitive string prefix for X.
b) X is from the Prefixes list and there is no item in the Source list for which X is a case-insensitive string prefix.
The completed merged list should be in the same sort order as the items in the original two lists.
My Solution:
public ArrayList<String> merge(List<String> srcList, List<String> preList) {
// If Prefixes list is empty then there cannot be a new merge list
if (preList.isEmpty()) {
return null;
}
int i = 0, j = 0;
int sourcesListSize = srcList.size();
int prefixesListSize = preList.size();
ArrayList<String> mergeList = new ArrayList<String>();
// Loop through Sources list until end of the list is reached
//ASSUMPTION: Both SourceList and PrefixList are already sorted.
while (i < sourcesListSize && j<prefixesListSize) {
mergeList.add(preList.get(j).concat(srcList.get(i)));
i++;
j++;
}
// If Prefixes list still have items, then add it to mergeList
while (j < prefixesListSize) {
mergeList.add(preList.get(j));
j++;
}
return mergeList;
}
Input:
- Source list:
{"pple","ow","enver",pic,"ull"} - PrefixList:
{"a","c","d","e","f"}
MergeList={"apple",cow","denver","epic","full"}
Is my understanding correct? Is there any best other solution?
Since this is homework I’ll try not to give too much away, but per the definition of prefix, here are some examples:
Based on that, what will the MergeList be for the following? Hint: there will be items from both SourceList and PrefixList in the correct MergeList. Post your solution and I’ll critique it. Once you understand how this part works, you’ll have a much better idea of how to code the solution.