What is the most efficient way to detect if a string contains a number of consecutive duplicate characters in C#?

前端 未结 6 1351
無奈伤痛
無奈伤痛 2021-02-15 22:24

For example, a user entered \"I love this post!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\"

the consecutive duplicate exclamation mark \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" should b

6条回答
  •  天涯浪人
    2021-02-15 23:25

    Can be done in O(n) easily: for each character, if the previous character is the same as the current, increment a temporary count. If it's different, reset your temporary count. At each step, update your global if needed.

    For abbccc you get:

    a => temp = 1, global = 1
    b => temp = 1, global = 1
    b => temp = 2, global = 2
    c => temp = 1, global = 2
    c => temp = 2, global = 2
    c => temp = 3, global = 3
    
    => c appears three times. Extend it to get the position, then you should be able to print the "ccc" substring.
    

    You can extend this to give you the starting position fairly easily, I'll leave that to you.

提交回复
热议问题