Isomorphic Strings

Isomorphic Strings

Medium Python Strings 11 views
Explanation Complexity

Problem Statement

Input has two strings s and t are provided (same length). Two strings are isomorphic if each character in s can be mapped to exactly one character in t and vice-versa. Output YES or NO.

Input Format

Two lines: s then t.

Output Format

YES or NO.

Example

egg
add
YES

Constraints

1

Input / Output Format

Input Format
Two lines: s then t.
Output Format
YES or NO.
Constraints
1

Examples

Input:
egg add
Output:
YES

Example Solution (Public)

Python
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
s=lines[0].strip()
t=lines[1].strip()
if len(s)!=len(t):
  sys.stdout.write('NO')
else:
  st={}
  ts={}
  ok=True
  for a,b in zip(s,t):
    if a in st and st[a]!=b:
      ok=False
      break
    if b in ts and ts[b]!=a:
      ok=False
      break
    st[a]=b
    ts[b]=a
  sys.stdout.write('YES' if ok else 'NO')

Official Solution Code

import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
s=lines[0].strip()
t=lines[1].strip()
if len(s)!=len(t):
  sys.stdout.write('NO')
else:
  st={}
  ts={}
  ok=True
  for a,b in zip(s,t):
    if a in st and st[a]!=b:
      ok=False
      break
    if b in ts and ts[b]!=a:
      ok=False
      break
    st[a]=b
    ts[b]=a
  sys.stdout.write('YES' if ok else 'NO')
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.