YAKOVM
YAKOVM

Reputation: 10153

length of sub-sequence in the string

I need to implement lastSeq function,which gets as argument string str and char chr and returns the length of last sequence of repeated chr (the sequence can be of any length) for example: lastSeq("abbaabbbbacd",'a') should return 1
lastSeq("abbaabbbbacd",'b') should return 4 lastSeq("abbaabbbbacd",'t') should return 0

Is there C++ function which can solve it?

Upvotes: 1

Views: 138

Answers (2)

paper.plane
paper.plane

Reputation: 1197

int lastSeq(char *str, char chr)  
{  
    int i = strlen(str);  
    int l = 0;  

    while(--i>=0)  
       if(*(str + i) == chr && ++l)  
          break;

    while(--i>=0 && chr == *(str + i) && ++l);  

    return l;  
}

Upvotes: 1

Sylvain Defresne
Sylvain Defresne

Reputation: 44493

This appear to be homework, so I'm just going to give you direction so that you can find the answer by yourself.

First, how would you do it yourself, without a computer to give the correct result for your samples. From those manual run, how would you generalize then in simple steps so that you can solve the problem for all different inputs.

By this point you should have a rough algorithm to solve the problem. What do you know about storage of string in C++, and the method that are available from that class? Can some one them be used to solve some of the steps of your algorithm?

Try to write a program using those function, to compile it and to run it. Do you get the expected result? If not, can you try to print intermediate state (using std::cout << "Some value: " << variable << "\n";) to try to debug it.

Once you have done all of that, and if you are still having issues, update your question with your code, and we'll be able to give you more directed help.

Upvotes: 6

Related Questions