Reputation: 1198
I want to check if the target string contains string in collections. And match the longest one. E.g.
Target string: str = "eignelaiwgn"
Collection strings: eig
, a
, eb
, eigne
, eignep
The result needs to be eigne
First I thought HashMap, but it is not sorted. So I try to put collection strings into ArrayList, then sort the list with string length. Then use for each
loop to check
if ( str.contains("eigne") )
This needs to loop list each time. Is there a better(faster) way to achieve this?
Upvotes: 1
Views: 5089
Reputation: 34460
Seems pretty straightforward with 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
This reads as: For every string in the collection, check if the target string contains it. If true, return the string with the max length. (As the collection might be empty, or as no string in the collection might match the filter, max
returns an Optional<String>
).
Upvotes: 2
Reputation: 297
You could use a suffix tree. Please follow this link: https://www.geeksforgeeks.org/pattern-searching-using-suffix-tree/
Upvotes: 0
Reputation: 15423
You could use a TreeSet
for the same.
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");
Now we iterate over the TreeSet
and find the first occurrence where the sub-string is present in the original string. Now since the TreeSet
is sorted in descending order of length, iteration will start from the highest to the lowest.
Upvotes: 1
Reputation: 3469
you can use LevensteinDistance() method of StringUtils class in java which will tell you the number of changes needed to change one String into another.you can print string with minimum changes needed, which is your answer. see this document -> LevenshteinDistance
Also look for differences method for same class which will tell the difference between the two string.
Upvotes: 0