1153. String Transforms Into Another String - cocoder39/coco39_LC GitHub Wiki
1153. String Transforms Into Another String
scenarios:
- each char in str1 cannot point to different chars
- if the conversion form a linked list (ie, no cycle), then just need to do backward conversion for abc -> bcd, first form a graph a->b->c->d, then backward conversion: c->d, b->c, a->b
- if the conversion form a cycle, abc -> bca, a temp char need to be used to break the cycle a->temp, c->a, b->c, temp->b
- multiple different chars in str1 point to same char in str2. This scenario is covered by #2
Solution below handles 2 and 3 by return len(set(list(str2))) < 26
:
for linked list, len(set(list(str2))) must be less than 26
for cycle, len(set(list(str2))) < 26 indicates there is temp char available for conversion
The only scenario cannot be covered is when str1 == str2
class Solution:
def canConvert(self, str1: str, str2: str) -> bool:
if str1 == str2:
return True
graph = {}
for ch1, ch2 in zip(str1, str2):
if ch1 in graph and graph[ch1] != ch2:
return False
graph[ch1] = ch2
return len(set(list(str2))) < 26