2

I am trying to find the length of the longest consecutive character('!') in a string.

For example, input:

!!!!Hello!!

Output:

4

I am trying to solve this problem with recursion and this is my approach:

unsigned int length_of_longest_consecutive_dquotes(const char line[], int start)
{
    if (line[start] != '\0') {
        if (line[start] == '!') {
            return length_of_longest_consecutive_mark(line,start+1) + 1;
        }
        else
            return length_of_shortest_consecutive_mark(line,start+1);
    }

    return 0;
}

Where Start = 0; I am not able to figure out what shall I implement in the length_of_shortest_consecutive_dquotes(line,start) function. Please suggest me some better algorithm for implementing it. Thanks!

James Z
  • 12,209
  • 10
  • 24
  • 44
user237252
  • 63
  • 6

1 Answers1

2

At each iteration you have to remember the preceding parsed character, and then compare with the first of the remaining part of the array. If they are the same then add one to the length of the current possible longest sequence, if not length is 1 (the length of a new possible longest sequence). Of course you also have to remember the highest length.

Something like that?

#include <iostream>

unsigned int length_of_longest_consecutive(char previous,const char *line,int ll,int current_length)
{

    if (*line==0) return ll>current_length?ll:current_length;
    if (*line==previous) {
        return length_of_longest_consecutive(*line,line+1,ll,current_length+1);
    }
    return length_of_longest_consecutive(*line,line+1,ll>current_length?ll:current_length,1);
}

int main() {
    const char *a = "a!!!b!!!!ccccc!!d";
    std::cout << length_of_longest_consecutive('\0',a,0,0) << std::endl;
}
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69