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

    Example 1:

    Input: s = "egg", t = "add"
    Output: true
    

    Example 2:

    Input: s = "foo", t = "bar"
    Output: false

    Example 3:

    Input: s = "paper", t = "title"
    Output: true

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

    用hashmap,key是s[i],value是t[i]

    注意:如果map中已经存在s[i]这个key,不能再更新其value;由于一个value也只能对应一个key,如果map中已经存在s[i]对应的value,则无法添加新的映射到value的key

    时间:O(N),空间:O(N)

    class Solution {
        public boolean isIsomorphic(String s, String t) {
            HashMap<Character, Character> map = new HashMap<>();
            for(int i = 0; i < s.length(); i++) {
                if(map.containsKey(s.charAt(i)) && map.get(s.charAt(i)) == t.charAt(i))
                    continue;
                else if(!map.containsValue(t.charAt(i)) && !map.containsKey(s.charAt(i)))
                    map.put(s.charAt(i), t.charAt(i));
                else
                    return false;
            }
            return true;
        }
    }
  • 相关阅读:
    并发编程--锁--锁的理解及分类
    String -- 从源码剖析String类
    Spring 抽象的缓存包 spring-cache
    小白学做菜笔记
    使用Lists.partition切分性能优化
    String--常见面试题
    常用的Linux命令
    去除字符串中的空格
    微信小程序切换选中状态
    微信小程序面试题总结
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10059982.html
Copyright © 2011-2022 走看看