알고리즘
Make String a Subsequence Using Cyclic Increments
짬뽕얼큰하게
2025. 2. 24. 08:54
Leetcode Problem:
Summary
- Given two strings, check if str2 can be made a subsequence of str1 by performing the operation at most once.
Approach
- The approach used is to iterate over each character in str1 and check if it is equal to the current character in str2 or the next character in str1 (cyclically)
- If it is, increment the pointer for str2.
Complexity
- O(n), where n is the length of str1
Explanation
- The solution iterates over each character in str1 and checks if it is equal to the current character in str2 or the next character in str1 (cyclically)
- If it is, increment the pointer for str2
- If the pointer for str2 reaches the end of str2, return true
- Otherwise, return false.
Solution Code:
class Solution {
public:
bool canMakeSubsequence(string str1, string str2) {
int j = 0;
for(int i = 0 ; i < str1.size(); i++){
char next = str1[i] == 'z' ? 'a' : str1[i] + 1;
if(j < str2.size() && (str1[i] == str2[j] || str2[j] == next)){
j++;
}
}
if (j >= str2.size()) return true;
return false;
}
};
class Solution {
public:
bool canMakeSubsequence(string str1, string str2) {
int j = 0;
for(int i = 0 ; i < str1.size(); i++){
char next = str1[i] == 'z' ? 'a' : str1[i] + 1;
if(j < str2.size() && (str1[i] == str2[j] || str2[j] == next)){
j++;
}
}
if (j >= str2.size()) return true;
return false;
}
};