【Leetcode】Isomorphic Strings

题目链接: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.

思路:

用HashMap存储字符之间映射关系,要注意是双向映射即a映射到b,b也要映射到a,用hashmap要判断两次。

算法:

	public boolean isIsomorphic(String s, String t) {
		char strs[] = s.toCharArray();
		char patterns[] = t.toCharArray();
		Map<Character, Character> maps = new HashMap<Character, Character>();

		for (int i = 0; i < strs.length; i++) {
			if (maps.containsKey(strs[i])) {
				if (!(maps.get(strs[i]).charValue() == patterns[i])) {
					return false;
				}
			} else {
				maps.put(strs[i], patterns[i]);
			}
		}

		maps.clear();
		for (int i = 0; i < patterns.length; i++) {
			if (maps.containsKey(patterns[i])) {
				if (!(maps.get(patterns[i]).charValue() == strs[i])) {
					return false;
				}
			} else {
				maps.put(patterns[i], strs[i]);
			}
		}
		return true;
	}


你可能感兴趣的:(【Leetcode】Isomorphic Strings)