2825. Make String a Subsequence Using Cyclic Increments #912
-
Topics: You are given two 0-indexed strings In an operation, you select a set of indices in Return Note: A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to check if we can make Explanation:
Let's implement this solution in PHP: 2825. Make String a Subsequence Using Cyclic Increments <?php
/**
* @param String $str1
* @param String $str2
* @return Boolean
*/
function canMakeSubsequence($str1, $str2) {
$n = strlen($str1);
$m = strlen($str2);
$i = 0;
$j = 0;
// Traverse through both strings
while ($i < $n && $j < $m) {
// Check if characters match or can be incremented to match
if ($str1[$i] == $str2[$j] || (ord($str1[$i]) + 1 - ord('a')) % 26 == (ord($str2[$j]) - ord('a')) % 26) {
// Move both pointers
$i++;
$j++;
} else {
// Move pointer i in str1
$i++;
}
}
// If j reached the end of str2, we managed to match all characters
return $j == $m;
}
// Example Usage
$str1 = "abc";
$str2 = "ad";
echo canMakeSubsequence($str1, $str2) ? 'true' : 'false'; // Output: true
$str1 = "zc";
$str2 = "ad";
echo canMakeSubsequence($str1, $str2) ? 'true' : 'false'; // Output: true
$str1 = "ab";
$str2 = "d";
echo canMakeSubsequence($str1, $str2) ? 'true' : 'false'; // Output: false
?> Explanation:
Time Complexity:
Space Complexity:
This solution efficiently checks if it's possible to make |
Beta Was this translation helpful? Give feedback.
We need to check if we can make
str2
a subsequence ofstr1
by performing at most one cyclic increment operation on any characters instr1
:Explanation:
i
forstr1
andj
forstr2
.str1[i]
matchesstr2[j]
, we move both pointers forward.str1[i]
can be incremented to matchstr2[j]
(cyclically), we try to match them and then move both pointers.i
forstr1
.str2
, then it is possible to makestr2
a subsequence ofstr1
, otherwise not.Let's implement this solution in PHP: 2825. Make String a Subsequence Using Cyclic Increments