Find the number of occurrences of a subsequence in a string

前端 未结 9 1577
粉色の甜心
粉色の甜心 2020-12-04 05:13

For example, let the string be the first 10 digits of pi, 3141592653, and the subsequence be 123. Note that the sequence occurs twice:



        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 05:38

    How to count all three-member sequences 1..2..3 in the array of digits.

    Quickly and simply

    Notice, we need not FIND all sequences, we need only COUNT them. So, all algorithms that search for sequences, are excessively complex.

    1. Throw off every digit, that is not 1,2,3. The result will be char array A
    2. Make parallel int array B of 0's. Running A from the end, count for the each 2 in A the number of 3's in A after them. Put these numbers into the appropriate elements of B.
    3. Make parallel int array C of 0's.Running A from the end count for the each 1 in A the sum of B after its position. The result put into the appropriate place in C.
    4. Count the sum of C.

    That is all. The complexity is O(N). Really, for the normal line of digits, it will take about twice the time of the shortening of the source line.

    If the sequence will be longer, of , say, M members, the procedure could be repeated M times. And complexity will be O(MN), where N already will be the length of the shortened source string.

提交回复
热议问题