Skip to main content
Back to problems
#1153
Hard Algorithms

String transforms into another string

Hash Table String Graph Theory
34.6% acceptance
Mar 31, 2026
888
339
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn can_convert(str1: String, str2: String) -> bool {
    if str1 == str2 {
      return true;
    }
    let mut mapping = [0u8; 26];
    let mut has_mapping = [false; 26];
    let b1 = str1.as_bytes();
    let b2 = str2.as_bytes();
    for i in 0..b1.len() {
      let c1 = (b1[i] - b'a') as usize;
      let c2 = b2[i] - b'a';
      if has_mapping[c1] {
        if mapping[c1] != c2 {
          return false;
        }
      } else {
        has_mapping[c1] = true;
        mapping[c1] = c2;
      }
    }
    // Need at least one unused char in str2 to use as temp
    let mut used = [false; 26];
    for &b in b2 {
      used[(b - b'a') as usize] = true;
    }
    used.iter().filter(|&&x| x).count() < 26
  }
}