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.

题目很简单,稍微注意一点:

这里s,t要相互比较才行,不然仅仅是isomorphic(s,t)的话,"ab","aa"也满足,事实是不符合题意的。


代码如下:

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


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