[leetcode]Isomorphic Strings

来源:互联网 发布:前海金融管理学院 知乎 编辑:程序博客网 时间:2024/05/29 18:51

题目描述如下:

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.

题目真的不难,然而po主一开始用了数组去代替map然后在各种边界上出bug啊(感觉还是因为初始值的限制,加上昨天晚上实在是太困了所以脑子回路有点问题WA了很多遍),后来乖乖选择了用map进行记录,然后想偷懒不用两次映射结果最后反而TLE了。没办法,最后还是用了双向映射,代码如下:

public class Solution {    public boolean isIsomorphic(String s, String t) {        if (s.length() == 1) {            return s.equals(t);        }        Map<Character, Character> isomorphicMap = new HashMap<Character, Character>();        char s_mapKey, t_mapKey;        for (int i = 0; i < s.length(); i++) {            s_mapKey = s.charAt(i);            t_mapKey = t.charAt(i);            if (isomorphicMap.containsKey(s_mapKey)) {                if (!(isomorphicMap.get(s_mapKey).equals(t_mapKey)))                    return false;            } else {                isomorphicMap.put(s_mapKey, t_mapKey);            }        }        isomorphicMap.clear();        for (int i = 0; i < s.length(); i++) {            s_mapKey = s.charAt(i);            t_mapKey = t.charAt(i);            if (isomorphicMap.containsKey(t_mapKey)) {                if (!(isomorphicMap.get(t_mapKey).equals(s_mapKey)))                    return false;            } else {                isomorphicMap.put(t_mapKey, s_mapKey);            }        }        return true;    }}

题目链接:https://leetcode.com/problems/isomorphic-strings/

0 0
原创粉丝点击