码迷,mamicode.com
首页 > 其他好文 > 详细

Isomorphic Strings

时间:2015-06-28 21:34:52      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

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.

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.

解题思路:

同为字符串对比的题目,这题和前面的anagrams有点类似,但是还是有区别的。

大意是,t和s的字符是否能够一一map。思路也比较清晰,因为s和t长度相等,我们可以i从0到length()-1,一个个比较就是了。

用一个map记录前面已经建立的对应关系。如果t的当前字符在map中已经建立过了,就直接拿出来看,当前s的字符和map中存的对应关系是否一样。不一样就能直接返回false了。如果t的当前字符在map中没有建立过,还要反过来看。s的当前字符是不是以前被别的字符已经映射了?这点特别重要!建立过了,就返回false,否则就将这个新的对应关系put到map里。

第二个检查,可以用直接看map.containsValue()。但是必须注意,map的这个方法是O(n)的,而不是O(1)。那么我们可以借助另一个数据结构set,获得O(1)的时间。

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> map = new HashMap<Character, Character>();

        for(int i = 0; i < s.length(); i++) {
            if(map.containsKey(t.charAt(i))) {
                if(map.get(t.charAt(i)) != s.charAt(i)) {
                    return false;
                }
            } else {
                if(map.containsValue(s.charAt(i))) {
                    return false;
                }
                map.put(t.charAt(i), s.charAt(i));
            }
        }
        return true;
    }
}

用set的方法

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character, Character> map = new HashMap<Character, Character>();
        Set<Character> set = new HashSet<Character>();
        
        for(int i = 0; i < s.length(); i++) {
            if(map.containsKey(t.charAt(i))) {
                if(map.get(t.charAt(i)) != s.charAt(i)) {
                    return false;
                }
            } else {
                if(set.contains(s.charAt(i))) {
                    return false;
                }
                map.put(t.charAt(i), s.charAt(i));
                set.add(s.charAt(i));
            }
        }
        return true;
    }
}

 

Isomorphic Strings

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4606086.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!