RSS

Write a function that returns the longest run of a letter in a string. e.g. “cccc” in the string “abccccdef”

Fri, Mar 5, 2010

Algorithm

#include
using namespace std;
int main()
{
         char str[]=”axxxxxxxxxxxxxxdefffffgasdfgafgasdh”;
         int i=0,j=0,index=0;
         int c1=0,cmax=0;
         //If the first character present then
         //initialize the number of occurance
         if(str[0])
         {
           c1=1;
           cmax=1;
           i=1;
         }
 
         while(str[i]!=NULL)
         {
           //If there is a match then increment the count
           //increment the i always but not j
           if(str[i]==str[j])
             c1++;
           //If the matching condition breaks then
           //go to else loop
           else
           {
             //If the count is greater than maximum count
             //till now then increment the occurance and also
             //mark the index from j value to keep track of the
             //character
             if(c1 > cmax)
             {
               cmax = c1;
               index=j;
             }
             //In any case reinitialize c1 and j to keep track
             //a fresh character

             c1=1;
             j=i;
           }
           i++;
         }
         //This part is for ending verification
         //It can be optimized
         if(c1>cmax)
         {
           cmax=c1;
           index=j;
         }
         cout<          return 0;
}

Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Other Posts:

This post was written by:

eXclusiveMinds - who has written 500 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.