N
N
Nikita2020-12-14 11:04:16
Java
Nikita, 2020-12-14 11:04:16

How to find the longest substring in a string that occurs less than 2 times?

There is a string, how to find a substring in it that occurs at least 2 times and is the longest of such substrings.

I don’t ask for a ready-made solution, I can’t understand the search algorithm.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Roo, 2020-12-14
@xez

1. Divide the length of the string by 2 - we get the first possible variant of the length of the substring.
2. In the loop, slowly decreasing the length of the substring, we are looking for
a. Possible substrings.
b. The frequency of their occurrence in the source string (for example, adding in a Map).
Example:
String: aabcdaa
Step one: possible length 7/2 -> three characters.
Step two: select lines of three characters -> aab, abc, bcd, daa -> no repetitions.
Step three: select lines of two characters -> aa, ab, bc, cd, aa -> found the string aa - the longest, which occurs 2 times.

T
Therapyx, 2020-12-14
@Therapyx

hmm, it depends on input. If you do not resort to certain features of languages, but abstract by what is almost everywhere, then I would most likely do this:
1) I would make a map, hashmap and (co.) in the form of "String, int", where the string will be part broken substring, and int is a counter
2) I would take a substring and split it partially, adding it to this data structure with an initial counter 1, but
2.2) Adding to do a check if there is such a pattern already in it? if yes, then increase the counter
2.3) If not, then add to the new index with the base counter.
3) at the very end, you run through the data structure, where the counter is 2 and higher, while calculating the maximum from the number of characters in the substrings

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question