[LeetCode] Make String a Subsequence Using Cyclic Increments

2825. Make String a Subsequence Using Cyclic Increments

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
bool canMakeSubsequence(string str1, string str2) {
int j = 0;
for(int i = 0; i < str1.size(); i++) {
if(j == str2.size()) return true;
if(str1[i] == str2[j] or (str1[i] + 1 - 'a') % 26 + 'a' == str2[j]) j += 1;
}
if(j == str2.size()) return true;
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/08/20/PS/LeetCode/make-string-a-subsequence-using-cyclic-increments/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.