Search code examples
phpstringfor-looplongest-substring

Is there anyway to repeat the biggest segment of continuous segment of repeat using php?


I want to put the input like "RKKRRRRK" and try to get the output like largest continuous segment.. Suppose my input may be "RKKKR" then my program will display 'KKK' is the largest continuous segment.. and then it also display the count is 3..

I've already write the code for counting 'R' values.. now i want this program also... need help anyone help me.. thanks in advance.

Here the code:-

<?php

    function numberOfR($string1) 
    {

        for($i=0;$i <strlen($string1);$i++)
        {
            if($string1[$i]!='K') 
            {
                $count++;
            }
        }
        return $count;
    }
    $return_value= numberOfR("RKKRK");
    echo "R's count is:";
    echo $return_value;
?>

Solution

  •     <?php
        function getLongetSegment($string) {
            $currentSegmentChar='';
            $currentSegment="";
            $biggestSegment="";
            $current_length=0;
            $biggest_length=0;
            for($i=0;$i<strlen($string);$i++) {
                $char = $string[$i];
                    if($char != $currentSegmentChar || $currentSegmentChar == '') {
                        if($current_length >= $biggest_length) {
                            $biggestSegment = $currentSegment;
                            $biggest_length = $current_length;
                        }
                        $currentSegmentChar = $char;
                        $currentSegment = $char;
                        $current_length = 1;
                    }
                    elseif($currentSegmentChar != '') {
                        $currentSegment .= $char;
                        $current_length++;
                    }
            }
            if($current_length >= $biggest_length) {
                $biggestSegment = $currentSegment;
            }
            return array("string" => $biggestSegment,"length" => $biggest_length);
        }   
        print_r(getLongetSegment("RKKRGGG"));
    ?>
    

    Result: GGG