zoukankan      html  css  js  c++  java
  • 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.

    Note:
    You may assume both s and t have the same length.


    解题思路:

     isomorphic a 同形的,同构的

    此题非常类似 Leetcode Word Pattern .

    用HashMap, s 里是key, t 里是value. 每次比较,首先检查是否已有该key, 若有,检查对应value 是否相等,不等 return false; 若没有,检查value 是否已存在map里,若有,则two characters may map to the same character, return false, 若没有,put to map.


    Java code:

    public boolean isIsomorphic(String s, String t) {
            if(s.length() != t.length()){
                return false;
            }
            Map<Character, Character> map = new HashMap<Character, Character>();
            for(int i = 0; i < t.length(); i++) {
                if(map.containsKey(s.charAt(i))){
                    if(map.get(s.charAt(i)) != t.charAt(i)){
                        return false;
                    }
                }else {
                    if(map.containsValue(t.charAt(i))){
                        return false;
                    }else {
                        map.put(s.charAt(i), t.charAt(i));
                    }
                }
            }
            return true;
        }
  • 相关阅读:
    socket错误码获取
    代码整洁之道读书笔记函数
    算法学习之堆排序
    包含与继承区别
    提高 LayerBacked Memory Use
    RenderBuffer
    算法学习之快速排序
    NSTimer
    DNS and BIND ... (转载) zhumao
    Samba学习笔记(转载) zhumao
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4865670.html
Copyright © 2011-2022 走看看