Home >Backend Development >PHP Tutorial >Make String a Subsequence Using Cyclic Increments
2825. Make String a Subsequence Using Cyclic Increments
Difficulty: Medium
Topics: Two Pointers, String
You are given two 0-indexed strings str1 and str2.
In an operation, you select a set of indices in str1, and for each index i in the set, increment str1[i] to the next character cyclically. That is 'a' becomes 'b', 'b' becomes 'c', and so on, and 'z' becomes 'a'.
Return true if it is possible to make str2 a subsequence of str1 by performing the operation at most once, and false otherwise.
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:
Solution:
We need to check if we can make str2 a subsequence of str1 by performing at most one cyclic increment operation on any characters in str1:
Let's implement this solution in PHP: 2825. Make String a Subsequence Using Cyclic Increments
Explanation:
- Two Pointers: i and j are initialized to the start of str1 and str2, respectively.
- Matching Logic: Inside the loop, we check if the characters at str1[i] and str2[j] are the same or if we can increment str1[i] to match str2[j] cyclically.
- The cyclic increment condition is handled using (ord($str1[$i]) 1 - ord('a')) % 26 which checks if str1[i] can be incremented to match str2[j].
- Subsequence Check: If we have iterated through str2 completely (i.e., j == m), it means str2 is a subsequence of str1. Otherwise, it's not.
Time Complexity:
This solution efficiently checks if it's possible to make str2 a subsequence of str1 with at most one cyclic increment operation.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Make String a Subsequence Using Cyclic Increments. For more information, please follow other related articles on the PHP Chinese website!