LeetCode 1153. String Transforms Into Another String

原题链接在这里: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. 1 <= str1.length == str2.length <= 10^4
  2. Both str1 and str2 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 }
复制代码

 

posted @   Dylan_Java_NYC  阅读(2993)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2016-02-29 LeetCode 286. Walls and Gates
点击右上角即可分享
微信分享提示