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;
        }
    }
  • 相关阅读:
    WordPress fonts.useso.com加载慢解决办法
    ecshop 需要修改权限的文件夹及文件
    手机前端框架UI库(Frozen UI、WeUI、SUI Mobile)
    apache2配置rewrite_module
    wordpress htaccess伪静态设置
    linux whereis 快速查找命令
    Linux下的PS和grep的使用
    [转]group by 后使用 rollup 子句总结
    Maven配置国内镜像仓库
    清除电脑垃圾.bat
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6612961.html
Copyright © 2011-2022 走看看