[LeetCode] 2825. Make String a Subsequence Using Cyclic Increments

CNoodle發表於2024-12-05

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.

Example 1:
Input: str1 = "abc", str2 = "ad"
Output: true
Explanation: Select index 2 in str1.
Increment str1[2] to become 'd'.
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.

Example 2:
Input: str1 = "zc", str2 = "ad"
Output: true
Explanation: Select indices 0 and 1 in str1.
Increment str1[0] to become 'a'.
Increment str1[1] to become 'd'.
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.

Example 3:
Input: str1 = "ab", str2 = "d"
Output: false
Explanation: In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once.
Therefore, false is returned.

Constraints:
1 <= str1.length <= 105
1 <= str2.length <= 105
str1 and str2 consist of only lowercase English letters.

迴圈增長使字串子序列等於另一個字串。

給你一個下標從 0 開始的字串 str1 和 str2 。

一次操作中,你選擇 str1 中的若干下標。對於選中的每一個下標 i ,你將 str1[i] 迴圈 遞增,變成下一個字元。也就是說 'a' 變成 'b' ,'b' 變成 'c' ,以此類推,'z' 變成 'a' 。

如果執行以上操作 至多一次 ,可以讓 str2 成為 str1 的子序列,請你返回 true ,否則返回 false 。

注意:一個字串的子序列指的是從原字串中刪除一些(可以一個字元也不刪)字元後,剩下字元按照原本先後順序組成的新字串。

思路

思路是同向雙指標,一個指標指向 str1,一個指標指向 str2。如果str1[i] == str2[j],則 i 和 j 同時向後移動,直到 str1[i]!= str2[j]。當 str1[i]!= str2[j] 的時候,因為題目只允許我們修改 str1 中的字元,所以我們只能移動 i 指標,判斷他是否能和 str2[j] 相等。

複雜度

時間O(n)
空間O(1)

程式碼

Java實現

class Solution {
    public boolean canMakeSubsequence(String str1, String str2) {
        int m = str1.length();
        int n = str2.length();
        // corner case
        if (n > m) {
            return false;
        }

        // normal case
        int i = 0;
        int j = 0;
        while (i < m && j < n) {
            char a = str1.charAt(i);
            char b = str2.charAt(j);
            if (a == b || (a + 1 - 'a') % 26 == b - 'a') {
                j++;
            }
            i++;
        }
        if (j == n) {
            return true;
        }
        return false;
    }
}

相關文章