原题链接在这里:https://leetcode.com/problems/string-transforms-into-another-string/
题目:
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.
Note:
1 <= str1.length == str2.length <= 10^4
- Both
str1
andstr2
contain only lowercase English letters.
题解:
If two string equals, then return true.
If one character a is mapped to 2 different chars, then return false.
The order matters, in example 1, a->c, c->e. need to perform c->e first. Otherwise, a->c, becomes ccbcc, then c->e, it becomes eedee, which is not ccdee.
Or we need a temp char g a->g->c, first have a->g ggbcc, then c->e, ggbee. Last we have g->c, then ccbee.
Inorder to do this, we need one unused char in str2, which makes the size of str2 unique chars smaller than 26.
Time Complexity: O(n). n = str1.length().
Space: O(n).
AC Java:
1 class Solution { 2 public boolean canConvert(String str1, String str2) { 3 if(str1.equals(str2)){ 4 return true; 5 } 6 7 int n = str1.length(); 8 HashMap<Character, Character> hm = new HashMap<>(); 9 for(int i = 0; i < n; i++){ 10 char c1 = str1.charAt(i); 11 char c2 = str2.charAt(i); 12 if(hm.containsKey(c1) && hm.get(c1) != c2){ 13 return false; 14 } 15 16 hm.put(c1, c2); 17 } 18 19 return new HashSet<Character>(hm.values()).size() < 26; 20 } 21 }