leetcode- Isomorphic Strings

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.

方法二图例:

直接看代码分析:

package leetcode;

import java.util.*;

public class IsomorphicStrings {
    // 题目:All occurrences of a character....
    // 框架相同,即只要在某位置上出现相同字符,那么另一个单词相应位置也一定出现相同字符;
    // 像 palepr、 titlte这种情况,就返回false,可用相同字母替换的;
    public static boolean isIsomorphic(String sString, String tString) {
        /*
         * 方法一:直接用map if(s==null && t==null) return true;
         * if(s.length()!=t.length()) return false; //用键值对保存两个字符串的相应字符!good idea
         * HashMap<Character,Character> map = new HashMap<>(); int i=0;
         * while(i<s.length()){ //前面要分析,如果键值相同要怎么办?那么如果key相同,而value不同,就返回false
         * if(map.containsKey(s.charAt(i))){ char tmp = map.get(s.charAt(i));
         * if(tmp!=t.charAt(i)) return false; }else
         * if(map.containsValue(t.charAt(i))) return false; else{
         * //只有确保key不相同的时候才可以往里放键值对,所以放值一定是最后的步骤(当键不相同的时候才可以放)
         * map.put(s.charAt(i), t.charAt(i)); } i++; System.out.println(map); }
         *
         * return true;
         */
        /*
         * 方法二:这里是用两个数组去模拟HashMap
         * 新建两个s,t数组,其下标为自己当前的元素,但是存的值是对方的相应位置上的元素,建立起了映射关系
         *
         */
        char[] s = sString.toCharArray();
        char[] t = tString.toCharArray();

        int length = s.length;
        if (length != t.length)
            return false;

        char[] sm = new char[256];
        char[] tm = new char[256];

        for (int i = 0; i < length; i++) {
            char sc = s[i];
            char tc = t[i];
            if (sm[sc] == 0 && tm[tc] == 0) {
                sm[sc] = tc; // 关键idea!
                tm[tc] = sc;
            } else {
                if (sm[sc] != tc || tm[tc] != sc) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.print(isIsomorphic("papepr", "titlte"));
    }

}

态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
原文地址:https://www.cnblogs.com/neversayno/p/5407724.html