本文主要是介绍leetcode:(205) Isomorphic Strings(java),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package LeetCode_HashTable;/*** 题目:* 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.* Example 1:* Input: s = "egg", t = "add"* Output: true* Example 2:* Input: s = "foo", t = "bar"* Output: false* Example 3:* Input: s = "paper", t = "title"* Output: true* Note:You may assume both s and t have the same length.* 解题思路:* 把s中的字符作为键,t中的字符作为键值,用哈希表简历映射关系。* 如果哈希表中没有temp1这个键,同时也没有temp2这个键值,那么将temp1,temp2加入到哈希表中,* 若没有temp1,有temp2,不满足同构条件,返回false.* 如果哈希表中有temp1这个键,并且temp1的键值等于temp2,则进行下一次循环。* 若哈希表中有temp1这个键,但是temp1键值不等于temp2,不满足同构条件,返回false.*/import java.util.HashMap; public class IsIsomorphic_205_1021 {public boolean IsIsomorphic(String s, String t) {if (s == null || s.length() == 0) {return true;}if (s.length() != t.length()) {return false;}HashMap<Character, Character> map = new HashMap<>();for (int i = 0; i < s.length(); i++) {char temp1 = s.charAt(i);char temp2 = t.charAt(i);if (!map.containsKey(temp1)) {if (!map.containsValue(temp2)) {map.put(temp1, temp2);continue;} else return false;}else {if (map.get(temp1) == temp2) {continue;} else {return false;}}}return true;}public static void main(String[] args) {String s = "aba";String t = "baa";IsIsomorphic_205_1021 test = new IsIsomorphic_205_1021();boolean result = test.IsIsomorphic(s, t);System.out.println(result);} }
这篇关于leetcode:(205) Isomorphic Strings(java)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!