Input: str1 ="aabcc", str2 ="ccdee"Output: trueExplanation: Convert 'c' to 'e' then 'b' to 'd' then 'a' to 'c'. Note that the order of conversions matter.
Example 2:
1
2
3
Input: str1 ="leetcode", str2 ="codeleet"Output: falseExplanation: There is no way to transform str1 to str2.
Constraints:
1 <= str1.length == str2.length <= 10^4
str1 and str2 contain only lowercase English letters.
To transform str1 to str2, we need to map each character in str1 to the corresponding character in str2. If a character in str1 maps to more than one character in str2, it’s impossible. If the mapping forms a cycle and all 26 letters are used, we cannot break the cycle (since we have no spare character to use as a temporary placeholder).
import java.util.*;
classSolution {
publicbooleancanConvert(String str1, String str2) {
if (str1.equals(str2)) returntrue;
Map<Character, Character> map =new HashMap<>();
for (int i = 0; i < str1.length(); i++) {
char c1 = str1.charAt(i), c2 = str2.charAt(i);
if (map.containsKey(c1) && map.get(c1) != c2) returnfalse;
map.put(c1, c2);
}
Set<Character> set =new HashSet<>();
for (char c : str2.toCharArray()) set.add(c);
return set.size() < 26;
}
}
1
2
3
4
5
6
7
8
9
funcanConvert(str1: String, str2: String): Boolean {
if (str1 == str2) returntrueval map = mutableMapOf<Char, Char>()
for (i in str1.indices) {
if (map.containsKey(str1[i]) && map[str1[i]] != str2[i]) returnfalse map[str1[i]] = str2[i]
}
return str2.toSet().size < 26}
1
2
3
4
5
6
7
8
9
defcanConvert(str1: str, str2: str) -> bool:
if str1 == str2:
returnTrue mp = {}
for a, b in zip(str1, str2):
if a in mp and mp[a] != b:
returnFalse mp[a] = b
return len(set(str2)) <26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use std::collections::{HashMap, HashSet};
pubfncan_convert(str1: String, str2: String) -> bool {
if str1 == str2 { returntrue; }
letmut mp = HashMap::new();
let s1 = str1.as_bytes();
let s2 = str2.as_bytes();
for i in0..s1.len() {
iflet Some(&v) = mp.get(&s1[i]) {
if v != s2[i] { returnfalse; }
}
mp.insert(s1[i], s2[i]);
}
let set: HashSet<u8>= s2.iter().cloned().collect();
set.len() <26}
1
2
3
4
5
6
7
8
9
10
functioncanConvert(str1: string, str2: string):boolean {
if (str1===str2) returntrue;
constmp=newMap<string, string>();
for (leti=0; i<str1.length; i++) {
if (mp.has(str1[i]) &&mp.get(str1[i]) !==str2[i]) returnfalse;
mp.set(str1[i], str2[i]);
}
constset=newSet(str2);
returnset.size<26;
}