567. Permutation in String #667
-
Topics: Given two strings In other words, return Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use the sliding window technique with a frequency counter, rather than trying every possible substring permutation (which would be too slow for large inputs). Key Idea:
Steps:
Algorithm:
Let's implement this solution in PHP: 567. Permutation in String <?php
/**
* @param String $s1
* @param String $s2
* @return Boolean
*/
function checkInclusion($s1, $s2) {
$len1 = strlen($s1);
$len2 = strlen($s2);
// If s1 is longer than s2, s2 can't contain any permutation of s1
if ($len1 > $len2) {
return false;
}
// Initialize frequency arrays for s1 and the current window of s2
$count1 = array_fill(0, 26, 0);
$count2 = array_fill(0, 26, 0);
// Fill the count array for s1 and the first window of s2
for ($i = 0; $i < $len1; $i++) {
$count1[ord($s1[$i]) - ord('a')]++;
$count2[ord($s2[$i]) - ord('a')]++;
}
// Check if the first window matches
if ($count1 == $count2) {
return true;
}
// Start sliding the window
for ($i = $len1; $i < $len2; $i++) {
// Add the current character to the window
$count2[ord($s2[$i]) - ord('a')]++;
// Remove the character that is left out of the window
$count2[ord($s2[$i - $len1]) - ord('a')]--;
// Check if the window matches
if ($count1 == $count2) {
return true;
}
}
// If no matching window was found, return false
return false;
}
// Example usage
$s1 = "ab";
$s2 = "eidbaooo";
echo checkInclusion($s1, $s2) ? "true" : "false"; // Output: true
?> Explanation:
Time and Space Complexity:
This approach ensures that the solution is efficient even for larger inputs. |
Beta Was this translation helpful? Give feedback.
We can use the sliding window technique with a frequency counter, rather than trying every possible substring permutation (which would be too slow for large inputs).
Key Idea:
s1
is a substring ofs2
, both strings must have the same character frequencies for the letters present ins1
.s1
overs2
to check if the substring within the window is a permutation ofs1
.Steps:
s1
(i.e., count the occurrences of each character).s2
of size equal tos1
and check if the frequency of characters in the window matches the frequency of characters ins1
.