How to find repeating sequence of characters in a given array?

后端 未结 14 808
故里飘歌
故里飘歌 2020-12-02 12:42

My problem is to find the repeating sequence of characters in the given array. simply, to identify the pattern in which the characters are appearing.

          


        
14条回答
  •  渐次进展
    2020-12-02 13:13

    For your examples, my first approach would be to

    1. get the first character of the array (for your last example, that would be C)
    2. get the index of the next appearance of that character in the array (e.g. 9)
    3. if it is found, search for the next appearance of the substring between the two appearances of the character (in this case CARPENTER)
    4. if it is found, you're done (and the result is this substring).

    Of course, this works only for a very limited subset of possible arrays, where the same word is repeated over and over again, starting from the beginning, without stray characters in between, and its first character is not repeated within the word. But all your examples fall into this category - and I prefer the simplest solution which could possibly work :-)

    If the repeated word contains the first character multiple times (e.g. CACTUS), the algorithm can be extended to look for subsequent occurrences of that character too, not only the first one (so that it finds the whole repeated word, not only a substring of it).

    Note that this extended algorithm would give a different result for your second example, namely RONRON instead of RON.

提交回复
热议问题