A
A
amatoriste2017-02-23 22:24:14
PHP
amatoriste, 2017-02-23 22:24:14

Find the substring in a string that contains the maximum number of consecutive characters in this string?

For example.
There is a line

$str= 'abcccdefghijklm234nnnnopqqrerrstuvwxyz0156789';

You need to get a substring from it, with the maximum number of consecutive characters .
There is an idea:
to do it through preg_split() , find unique substrings and then go through the array and find the line with max. long.
But I got stuck with the regular season itself.
I can't figure out how to correctly write a sequence without repetition.
Maybe there is a kind person who can tell?))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Sokolov, 2017-02-23
@sergiks

It is necessary to move the ends of the segment: right R and left L. Initially, both are at zero.
We keep the current character set to check for repetitions. We remember the found maximum segment.
Move the right end by 1. If the character is not in the set, add it. If there is, we move L to the right for the found character. Before that, we check if we have found the next maximum.
Very crooked sleep-want implementation seems to work: Ideone
Old answer, please ignore: Move one character at a time. Remember found max. length. Compare character with previous character.
Equal – the length of the current segment is growing.
Not equal - the previous segment ended and a new one began. If the length is greater than the found maximum, the next candidate has been found. Remember its length and beginning. Remember the beginning of the next segment and count the length from 1.
Total walk once. No regulars needed.

X
xmoonlight, 2017-02-23
@xmoonlight

Don't listen to anyone : It 's Huffman .

I
Immortal_pony, 2017-02-24
@Immortal_pony

function findTheLongestSequence($str) {
    $sequences = [];
    $sequence = "";
    
    for ($letterIndex=0; $letterIndex<strlen($str); $letterIndex++) {
        $letter = $str[$letterIndex];
        $previousLetterIndex = ($letterIndex-1);
        $previousLetter = (isset($str[$previousLetterIndex]) ? $str[$previousLetterIndex] : null);

        if ($previousLetter === $letter) {
            if (!empty($sequence)) {
                $sequences[] = $sequence;
                $sequence = "";
            }
        } else {
            $sequence .= $letter;
        }
        
        if (strlen($str)-1 === $letterIndex && !empty($sequence)) {
            $sequences[] = $sequence;
        }
    }
    
    usort($sequences, function($someSequence, $otherSequence) {
        return strlen($otherSequence)-strlen($someSequence);
    });
    
    return $sequences[0];
}

PS If a programmer starts solving a problem with a regular expression, then he has two problems (s).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question