Problem description:
Evaluate the substring that appears the most frequently in a string. The length of the substring can be 1.
Analyze the problem:
At first glance, there seems to be nowhere to start. The efficiency of simple exhaustive operations is too low. As the input text grows, the time complexity and space complexity will soar to an unacceptable level.
We need to find rules.
Assume that there is a substring whose length is N, S appears most times. So what are the features of it?
- The number of occurrences of any substring in S is not less than that in S.
- S does not contain repeated substrings
- S does not contain repeated characters
- The occurrence times of each character and substring in S are the same as those in S.
"S does not contain repeated characters", "the number of occurrences of each character and substring in S is the same as that in S "!
With this conclusion, the problem is simple. Algorithm Description:
Locate the substring consisting of a single character with the highest number of occurrences in the text and put it in a queue,
Starts from the header of the queue and processes every substring S in the result set.
- Locate any position P where the substring appears in the text,
- Determines whether the character C following S in the text appears most frequently,
- If the number of occurrences of C is not the most, end.
- If C appears the most frequently, search for every second in the text and determine whether the followed character is C,
- If character C exists after every second in the text, put the substring generated by S + C into the result set,
- If the character S after S is not C in the text, it ends.
Until the end of the queue is reached.
Code:
# Pragma warning (disable: 4786)
# Include <iostream>
# Include <string>
# Include <deque>
# Define BUFFSIZE 1024
Using std: cout;
Using std: endl;
Using std: string