1153. String Transforms Into Another String

String Transforms Into Another String - LeetCode

Given two strings str1 and str2 of the same length, determine whether you can transform str1 into str2 by doing zero or more conversions. In one conversion you can convert all occurrences of one character in str1 to any other lowercase English character. Return true if and only if you can transform str1 into str2.

Example 1: Input: str1 = “aabcc”, str2 = “ccdee” Output: true Explanation: Convert ‘c’ to ‘e’ then ‘b’ to ’d' then ‘a’ to ‘c’. Note that the order of conversions matter. Example 2: Input: str1 = “leetcode”, str2 = “codeleet” Output: false Explanation: There is no way to transform str1 to str2.

Constraints:

1 <= str1.length == str2.length <= 104
str1 and str2 contain only lowercase English letters.

  • code
class Solution {
    public boolean canConvert(String str1, String str2) {
        int[] map = new int[26];
        Arrays.fill(map, -1);
        HashSet<Character> uni2 = new HashSet();
        
        for (int i = 0; i < str1.length(); ++i){
            if (map[str1.charAt(i) - 'a'] == -1){
                map[str1.charAt(i) - 'a'] = str2.charAt(i) - 'a';
                uni2.add(str2.charAt(i));
            }else{
                if (map[str1.charAt(i) - 'a'] != str2.charAt(i) - 'a'){
                    return false;
                }
            }
        }
        
        if (!str1.equals(str2) && uni2.size() == 26){
            return false;
        }
        return true;
    }
}