-
Notifications
You must be signed in to change notification settings - Fork 75
/
1153_String_Transforms_Into_Another_String
55 lines (44 loc) · 1.44 KB
/
1153_String_Transforms_Into_Another_String
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Leetcode 1153: String Transforms Into Another String
Detailed video explanation: https://youtu.be/BjJHV0rmfXY
=========================================================
C++:
----
class Solution {
public:
bool canConvert(string str1, string str2) {
if(str1 == str2) return true;
unordered_map<char, char> dp;
for(int i = 0; i < str1.length(); ++i){
if(dp.count(str1[i]) && dp[str1[i]] != str2[i])
return false;
dp[str1[i]] = str2[i];
}
return set(str2.begin(), str2.end()).size() < 26;
}
};
Java:
-----
class Solution {
public boolean canConvert(String str1, String str2) {
if(str1.equals(str2)) return true;
Map<Character, Character> dp = new HashMap();
for(int i = 0; i < str1.length(); ++i){
char c1 = str1.charAt(i), c2 = str2.charAt(i);
if(dp.containsKey(str1.charAt(i)) && dp.get(str1.charAt(i)) != str2.charAt(i))
return false;
dp.put(str1.charAt(i), str2.charAt(i));
}
return new HashSet<Character>(dp.values()).size() < 26;
}
}
Python3:
--------
class Solution:
def canConvert(self, str1: str, str2: str) -> bool:
if str1 == str2: return True
dp = {}
for i in range(len(str1)):
if str1[i] in dp and dp[str1[i]] != str2[i]:
return False
dp[str1[i]] = str2[i]
return len(set(str2)) < 26