Answer the question
In order to leave comments, you need to log in
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';
Answer the question
In order to leave comments, you need to log in
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.
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];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question