2981. Find Longest Special Substring That Occurs Thrice I #937
-
Topics: You are given a string A string is called special if it is made up of only a single character. For example, the string Return the length of the longest special substring of A substring is a contiguous non-empty sequence of characters within a string. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a brute force approach due to the small constraints of
Let's implement this solution in PHP: 2981. Find Longest Special Substring That Occurs Thrice I <?php
/**
* @param String $s
* @return Integer
*/
function maximumLength($s) {
$n = strlen($s);
// Iterate over substring lengths from longest to shortest
for ($len = $n; $len >= 1; $len--) {
$countMap = [];
// Sliding window to collect substrings of length $len
for ($i = 0; $i <= $n - $len; $i++) {
$substring = substr($s, $i, $len);
// Count the occurrences of each substring
if (!isset($countMap[$substring])) {
$countMap[$substring] = 0;
}
$countMap[$substring]++;
}
// Check if any special substring occurs at least 3 times
foreach ($countMap as $substring => $count) {
if ($count >= 3 && isSpecial($substring)) {
return $len; // Return the length of the substring
}
}
}
// If no special substring occurs at least 3 times
return -1;
}
/**
* Helper function to check if a substring is special
*
* @param $substring
* @return bool
*/
function isSpecial($substring) {
$char = $substring[0];
for ($i = 1; $i < strlen($substring); $i++) {
if ($substring[$i] !== $char) {
return false;
}
}
return true;
}
// Test cases
echo maximumLength("aaaa") . "\n"; // Output: 2
echo maximumLength("abcdef") . "\n"; // Output: -1
echo maximumLength("abcabcabc") . "\n"; // Output: 1
?> Explanation:
Complexity
This brute force approach is feasible given the constraints (n <= 50). |
Beta Was this translation helpful? Give feedback.
We can use a brute force approach due to the small constraints of
s
(length of up to 50). We'll:-1
.Let's implement this solution in PHP: 2981. Find Longest Special Substring That Occurs Thrice I