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;
        }
    }
  • 相关阅读:
    SSH服务附带----SFTP
    SSH附带的远程拷贝----SCP
    linux下的SSH服务
    model.form使用,配合form的钩子
    import_module 导入变量的包
    dir函数
    python爬虫之scrapy
    python爬虫之解析库Beautiful Soup
    django 过滤器,标签
    django 验证码实现
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6612961.html
Copyright © 2011-2022 走看看