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;
}
};
'알고리즘' 카테고리의 다른 글
Maximum Number of Integers to Choose From a Range I (0) | 2025.02.24 |
---|---|
Move Pieces to Obtain a String (0) | 2025.02.24 |
Adding Spaces to a String (0) | 2025.02.24 |
Check If a Word Occurs As a Prefix of Any Word in a Sentence (0) | 2025.02.24 |
Check If N and Its Double Exist (0) | 2025.02.24 |