Untitled

 avatar
unknown
plain_text
2 months ago
1.5 kB
4
Indexable
public class SubsequenceWithOneOperation {
    public static boolean canMakeSubsequence(String str1, String str2) {
        int n = str1.length(), m = str2.length();
        int i = 0, j = 0;
        boolean operationUsed = false;

        while (i < n && j < m) {
            if (str1.charAt(i) == str2.charAt(j)) {
                // If characters match directly, move both pointers
                i++;
                j++;
            } else {
                // If they don't match, we try using the operation
                if (!operationUsed && canIncrementTo(str1.charAt(i), str2.charAt(j))) {
                    operationUsed = true;
                    i++;
                    j++;
                } else {
                    i++;
                }
            }
        }

        // If we've matched all characters of str2, return true
        return j == m;
    }

    // Check if str1_char can be incremented to match str2_char
    private static boolean canIncrementTo(char str1_char, char str2_char) {
        return (str2_char - str1_char + 26) % 26 != 0;
    }

    public static void main(String[] args) {
        String str1 = "abc", str2 = "ad";
        System.out.println(canMakeSubsequence(str1, str2)); // true

        String str1_2 = "zc", str2_2 = "ad";
        System.out.println(canMakeSubsequence(str1_2, str2_2)); // true

        String str1_3 = "ab", str2_3 = "d";
        System.out.println(canMakeSubsequence(str1_3, str2_3)); // false
    }
}
Editor is loading...
Leave a Comment