Count Substring Occurrences
PHP
Medium
4 views
Problem Description
Count how many times pattern p occurs in s (overlaps allowed).
Input Format
Two lines: s then p.
Output Format
One integer count.
Official Solution
<?php
$inputText=rtrim(stream_get_contents(STDIN));
if($inputText==='') exit;
$inputLines=preg_split('/\\R/', $inputText);
$s=$inputLines[0] ?? '';
$p=$inputLines[1] ?? '';
if($p===''){ echo 0; exit; }
$c=0;
for($i=0;$i+strlen($p)<=strlen($s);$i++) if(substr($s,$i,strlen($p))===$p) $c++;
echo $c;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!