2825. Make String a Subsequence Using Cyclic Increments | Daily LeetCode Solution | Java #coding

preview_player
Показать описание
Solution Description:
The goal is to determine if str2 can be made a subsequence of str1 by either matching characters directly or after a cyclic increment (e.g., 'z' wraps around to 'a').

Approach:
Two Pointer Technique:

Use two pointers i and j to traverse str1 and str2 respectively.
i moves through every character of str1, while j advances only when a match for str2[j] is found in str1.
Matching Logic:

Characters match if they are the same or if the character from str1 increments cyclically to the character in str2.
Check the cyclic increment using modular arithmetic:
(c1 + 1 - 'a') % 26 == c2 - 'a'.
Early Termination:
Result:
Return false if the loop completes without matching all characters in str2.
Code Explanation:
Input: Two strings str1 and str2.
Output: Boolean indicating whether str2 can be a subsequence of str1.
Complexity:
Time: 𝑂(𝑛+𝑚), where 𝑛 is the length of str1 and 𝑚 is the length of str2.
Space: 𝑂(1), as no extra space is used beyond pointers and variables.

📅 Daily Solutions:
Subscribe for concise, step-by-step explanations and Java implementations of LeetCode's daily challenges!

👥 Join the Discussion:
How would you optimize this approach? Let us know in the comments below.
Рекомендации по теме
Комментарии
Автор

class Solution {
public boolean canMakeSubsequence(String str1, String str2) {
int i = 0, j = 0;
while(i < str1.length() && j < str2.length()) {
char c1 = str1.charAt(i);
char c2 = str2.charAt(j);

//Check if c1 matches c2 directly or after a single increment
if (c1 == c2 || (c1 + 1 - 'a') % 26 == c2 - 'a') {
j++;
}
i++;
}

//If we have matched all characters in str2, its a subsequence
return j == str2.length();
}
}

AlgoXploration
welcome to shbcf.ru