Skip to content

2825. Make String a Subsequence Using Cyclic Increments 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  bool canMakeSubsequence(string str1, string str2) {
    int i = 0;  // str2's index

    for (const char c : str1)
      if (c == str2[i] || ('a' + ((c - 'a' + 1) % 26)) == str2[i])
        if (++i == str2.length())
          return true;

    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public boolean canMakeSubsequence(String str1, String str2) {
    int i = 0; // str2's index

    for (final char c : str1.toCharArray())
      if (c == str2.charAt(i) || ('a' + ((c - 'a' + 1) % 26)) == str2.charAt(i))
        if (++i == str2.length())
          return true;

    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def canMakeSubsequence(self, str1: str, str2: str) -> bool:
    i = 0  # str2's index

    for c in str1:
      if c == str2[i] or chr(
              ord('a') + (string.ascii_lowercase.index(c) + 1) % 26) == str2[i]:
        i += 1
        if i == len(str2):
          return True

    return False