[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.


思路:

1、使用hash table;

2、将 s 中的字符和 t 中的字符建立映射关系:按照字符出现的顺序依次建立映射,且一个字符只能映射一个字符。故映射关系中键和值都是唯一的

3、如 foo, bar中, f -- b, o -- a, o -- r ,同一个 o 映射两个字符,所以不符合条件; 


Java 和 C++实现:

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<String, String> myMap = new HashMap<String, String>();
		for(int i = 0; i < s.length(); i ++){
			String tmps = s.substring(i,  i+1) ;
			String tmpt = myMap.get(tmps) ;
			if(tmpt != null){
				if(!tmpt.equals(t.substring(i,  i+1))) return false ;
			}else{
				if(myMap.containsValue(t.substring(i, i+1))) return false ;
				myMap.put(s.substring(i, i+1), t.substring(i, i+1)) ;
			}
		}
		return true ;
    }
}
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s == "" && t == "") return true ;
        map<char, char> mymap ;
		for(int i = 0; i < s.size(); i ++){
			if(mymap.find(s[i]) != mymap.end()){
				if(mymap[s[i]] != t[i]) return false ;
			}else{
				map<char, char>::iterator p ;
				for(p = mymap.begin(); p != mymap.end(); p ++){
					if(p->second == t[i]) return false ;
				}
				mymap[s[i]] = t[i];
			}
		}
    }
};



你可能感兴趣的:(java,LeetCode,C++)