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 }
  • 相关阅读:
    foreach在引用时的陷阱
    宝塔ngnix配置tp5
    三维空间建模方法之LOD模型算法
    Weblogic部署项目三种方式
    WebLogic使用总结
    SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
    BIM特点及格式文件说明
    BIM与GIS
    三维模型格式
    单点登录
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12382223.html
Copyright © 2011-2022 走看看