zoukankan      html  css  js  c++  java
  • leetcode 205. Isomorphic Strings 判断两个字符串能否互相转换 ---------- java

    Given two strings s and t, determine if they are isomorphic.

    Two strings are isomorphic if the characters in s can be replaced to get t.

    All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

    For example,
    Given "egg""add", return true.

    Given "foo""bar", return false.

    Given "paper""title", return true.

    用两个map记录一下对应的字母,由于必须是一一对应,所以用了两个map。

    public class Solution {
        public boolean isIsomorphic(String s, String t) {
            Map<Character, Character> map = new HashMap();
            Map<Character, Character> map2 = new HashMap();
            for (int i = 0; i < s.length(); i++){
                char ch = t.charAt(i);
                char sh = s.charAt(i);
                if (map.containsKey(sh)){
                    if (ch != map.get(sh)){
                        return false;
                    }
                } else {
                    
                    if (map2.containsKey(ch)){
                        return false;
                    }
                    map.put(sh, ch);
                    map2.put(ch, sh);
                }
            }
            return true;
        }
    }

    1、用一个map也可以,因为可以用containsValue()这个方法。

    2、也可以不用map,用数组就可以。注意的是数组大小,最好开两个256.

    3、也可以直接开一个数组,更简单。

    public class Solution {
        public boolean isIsomorphic(String s1, String s2) {
            int[] m = new int[512];
            for (int i = 0; i < s1.length(); i++) {
                if (m[s1.charAt(i)] != m[s2.charAt(i)+256]) return false;
                m[s1.charAt(i)] = m[s2.charAt(i)+256] = i+1;
            }
            return true;
        }
    }
  • 相关阅读:
    蓝桥杯——一步之遥,扩展gcd的应用
    质数唯一分解定理应用——多个数的最小公约数和最大公倍数
    蓝桥杯训练 ——天平称重
    蓝桥杯 奇怪的捐赠——进制的运用
    Kubernetes-基本概念
    Docker-基本概念
    虚拟化向容器化发展
    Kubernetes-服务连接和暴露(endpoints资源)
    Kubernetes-NodePort
    Kubernetes-Load Balancer
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6612961.html
Copyright © 2011-2022 走看看