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 }
  • 相关阅读:
    jsp和servlet的联系与区别
    tomcat会如何处理请求
    java中synchronized的关键字
    mybatis的动态sql
    spring自带的json转换工具,支持@ResponseBody注解
    layer一个web弹窗/层解决方案
    spring mvc出现乱码的问题
    hdu1010 Tempter of the Bone
    hdu 3342 Legal or Not
    ThreadPoolExecutor线程池执行器源码解析
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12382223.html
Copyright © 2011-2022 走看看