惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
WordPress大学
WordPress大学
D
DataBreaches.Net
腾讯CDC
小众软件
小众软件
B
Blog RSS Feed
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Y
Y Combinator Blog
V
V2EX
I
InfoQ
D
Docker
量子位
N
Netflix TechBlog - Medium
Recent Announcements
Recent Announcements
A
About on SuperTechFans
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog

博客园 - NickyYe

DYNAMIC LINK LIBRARY - DLL 分布式系统中Unique ID 的生成方法 201. Bitwise AND of Numbers Range 189. Rotate Array 187. Repeated DNA Sequences 167. Two Sum II - Input array is sorted Convert BST to Greater Tree Uncommon Words from Two Sentences Path Sum III Delete Node in a BST Sliding Window Maximum Find K Closest Elements C++ TUTORIAL - MEMORY ALLOCATION - 2016 多线程 Console Event Handling SetConsoleCtrlHandler() -- 设置控制台信号处理函数 SetConsoleCtrlHandler 处理控制台消息 总结open与fopen的区别 LevelDB
205. Isomorphic Strings
NickyYe · 2018-12-28 · via 博客园 - NickyYe

https://leetcode.com/problems/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

解题思路:

需要注意的是,要用两个map。用来处理"ab"->"aa"这种情况。

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if (s == null & t == null) {
            return true;
        }
        
        Map<Character, Character> s2t = new HashMap<Character, Character>();
        Map<Character, Character> t2s = new HashMap<Character, Character>();
        
        if (s.length() != t.length()) {
            return false;
        }
        
        for (int i = 0; i < s.length(); i++) {
            if (s2t.containsKey(s.charAt(i))) {
                if (s2t.get(s.charAt(i)) != t.charAt(i)) {
                    return false;
                }
            } else {
                if (t2s.containsKey(t.charAt(i))) {
                    return false;
                }
                s2t.put(s.charAt(i), t.charAt(i));
                t2s.put(t.charAt(i), s.charAt(i));
            }
        }
        return true;
    }
}