gpt4 book ai didi

java - 源和前缀的合并列表

转载 作者:行者123 更新时间:2023-12-01 15:25:29 25 4
gpt4 key购买 nike

我在学校遇到过以下问题,我已经按照我的理解解决了,解决方案如下。有人可以帮我提供更好的解决方案吗?

问题:

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.

我的解决方案:

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;

}

输入:

  • 来源列表:{"pple","ow","enver",pic,"ull"}
  • 前缀列表:{"a","c","d","e","f"}

MergeList={"apple",cow","denver","epic","full"}

我的理解正确吗?还有其他最好的解决方案吗?

最佳答案

由于这是家庭作业,我会尽量不要透露太多内容,但要根据 prefix 的定义。 ,以下是一些示例:

"a" is a prefix of "Apple"

"cow" is a prefix of "Cow"

"g" is not a prefix of "Zoo"

"col" is not a prefix of "cool"

基于此,MergeList 将用于以下内容?提示:正确的 MergeList 中将包含来自 SourceList 和 PrefixList 的项目。发布你的解决方案,我会批评它。一旦您了解了这部分的工作原理,您就会更好地了解如何编写解决方案。

SourceList : {"Apple","Pepper","Denver", "Garage", "Zoo"}

PrefixList : {"a","d","pe","xylophone","e"}

关于java - 源和前缀的合并列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10218481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com