我想检查目标字符串是否包含集合中的字符串。并匹配最长的那个。例如。
目标字符串:str = "eignelaiwgn"
集合字符串:eig、a、eb、eigne、eignep
结果需要为eigne
首先,我认为是HashMap,但它没有排序。因此,我尝试将集合字符串放入ArrayList中,然后根据字符串长度对列表进行排序。然后使用for each循环检查
if ( str.contains("eigne") )这需要每次循环list。有没有更好(更快)的方法来实现这一点?
发布于 2018-12-19 22:43:09
使用streams看起来非常简单:
String targetString = "eignelaiwgn";
Collection<String> collection = Arrays.asList("eig", "a", "eb", "eigne", "eignep");
Optional<String> longestMatch = collection.stream()
.filter(targetString::contains)
.max(Comparator.comparingInt(String::length));
longestMatch.ifPresent(System.out::println); // eigne如下所示:对于集合中的每个字符串,检查目标字符串是否包含它。如果为true,则返回最大长度的字符串。(由于集合可能为空,或者集合中没有与筛选器匹配的字符串,因此max将返回Optional<String>__)。
发布于 2018-12-19 15:02:15
您也可以使用TreeSet来实现同样的功能。
String str = "eignelaiwgn";
// Assuming that the 'sub-strings' are stored in a list
List<String> myList = Arrays.asList("eig", "a", "eb", "eigne", "eignep");
// Create a TreeSet that sorts based on descending order of length
Set<String> treeSet = new TreeSet<>((a, b) -> b.length() - a.length());
treeSet.addAll(myList);
String containsSub = treeSet.stream().filter(e -> str.contains(e))
.findFirst()
.orElse("Not found");现在,我们迭代TreeSet并找到第一个出现在原始字符串中的子字符串。现在,由于TreeSet是按长度降序排序的,因此迭代将从最高到最低开始。
发布于 2018-12-19 14:32:14
您可以在java中使用StringUtils类的LevensteinDistance()方法,它会告诉您将一个字符串更改为another.you所需的更改次数。只需最少的更改即可打印字符串,这就是您的答案。请参阅本文档-> LevenshteinDistance
还可以查找相同类的不同方法,这将区分两个字符串之间的差异。
https://stackoverflow.com/questions/53845672
复制相似问题