Home  >  Q&A  >  body text

java实现求字符串中出现次数最多的字串(单个字符不算)如"abcbcbcabc"的最终答案是bc 共出现了4 次,

如题java实现求字符串中出现次数最多的字串(单个字符不算)如"abcbcbcabc"的最终答案是bc 共出现了4 次,

怪我咯怪我咯2720 days ago422

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-18 10:17:27

    Suppose substring s appears x times in string S, then substring s2 of substring s will appear at least x times, or more

    A single character does not count, so here comes the problem. One of the substrings that appears most often must be a 2-character substring

    If you just want to find any one that meets the conditions, you only need to find a 2-character substring

    If you want to find all the substrings with the number of occurrences = the maximum number of occurrences, it will be a little more complicated.

    1. Assume that the length of the string S is N
    2. Combine the two adjacent characters in the string into N-1 substrings, and then count the 2-character byte strings to see which one appears the most.
    3. If there is no 2-character string with an equal number greater than 1, the search ends
    4. If there are multiple 2-character strings with equal times greater than 1, then compare these 2-character strings to see if there is the end of the first string Is equal to the string at the beginning of the second string. For example, ab appears 3 times and bc appears 3 times. Then abc may appear multiple times. If this happens, determine the number of occurrences of the 3-character string. If the number Less than the number of occurrences of a 2-character string, then the answer is a 2-character string, otherwise it may be a 3-character string.
    5. Then continue to detect 4, 5, and 6 character strings

    In addition, we need to clarify the statistical algorithm for the number of occurrences of a string. For example, does the substring aa in aaaaaa appear 3 times or 5 times?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:17:27

    It feels a little easier to get regular. If you don’t use regular expressions, it will definitely need to be solved iteratively or recursively

    reply
    0
  • Cancelreply