LeetCode-in-Java

2840. Check if Strings Can be Made Equal With Operations II

Medium

You are given two strings s1 and s2, both of length n, consisting of lowercase English letters.

You can apply the following operation on any of the two strings any number of times:

Return true if you can make the strings s1 and s2 equal, andfalse otherwise.

Example 1:

Input: s1 = “abcdba”, s2 = “cabdab”

Output: true

Explanation: We can apply the following operations on s1:

Example 2:

Input: s1 = “abe”, s2 = “bea”

Output: false

Explanation: It is not possible to make the two strings equal.

Constraints:

Solution

public class Solution {
    public boolean checkStrings(String s1, String s2) {
        return check(0, s1, s2) && check(1, s1, s2);
    }

    boolean check(int start, String s1, String s2) {
        int step = 2;
        int[] buf = new int[26];
        for (int i = start; i < s1.length(); i += step) {
            buf[s1.charAt(i) - 'a']++;
            buf[s2.charAt(i) - 'a']--;
        }
        for (int j : buf) {
            if (j != 0) {
                return false;
            }
        }
        return true;
    }
}