zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Knockout.js之初印象
    GroupBy之后加ToList和不加ToList有什么区别吗?
    值类型前加ref和out的区别
    引用类型前需要加ref?
    KEPServerEX连接SQLServer数据库操作
    nginx发布网站常用指令
    ASP.NET Core 布局 _Layout.cshtml
    ASP.NET Core-------appsettings.json文件配置与加载
    ASP.NET Core 入门程序
    ASP.NET.Core网站centerOS上部署发布
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12382223.html
Copyright © 2011-2022 走看看