ソースを参照

#feat:leetcode p205题题解

yangyi 2 週間 前
コミット
d40a138d1e
2 ファイル変更93 行追加0 行削除
  1. 46 0
      src/leetcode/p205/Solution.java
  2. 47 0
      src/leetcode/p205/SolutionTest.java

+ 46 - 0
src/leetcode/p205/Solution.java

@@ -0,0 +1,46 @@
+package leetcode.p205;
+
+import java.util.HashMap;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2026/3/8 16:02
+ * @Description: https://leetcode.cn/problems/isomorphic-strings/description
+ * 205. 同构字符串
+ */
+public class Solution {
+    /**
+     * 哈希表,直接映射
+     * 1.映射关系不存在,则添加映射关系
+     * 2.映射关系存在,则判断映射关系是否一致(不一致:false;一致:ture)
+     * @param s
+     * @param t
+     * @return
+     */
+    public boolean isIsomorphic(String s, String t) {
+        HashMap<Character, Character> map_s = new HashMap<>();
+        HashMap<Character, Character> map_t = new HashMap<>();
+        for (int i = 0; i < s.length(); i++) {
+            char sChar = s.charAt(i);
+            char tChar = t.charAt(i);
+            //双向映射都要检查
+            if (map_s.containsKey(sChar)) {
+                if (!map_s.get(sChar).equals(tChar)) {
+                    return false;
+                }
+            }else{
+                map_s.put(sChar,tChar);
+            }
+            if (map_t.containsKey(tChar)) {
+                if (!map_t.get(tChar).equals(sChar)) {
+                    return false;
+                }
+            }else {
+                map_t.put(tChar,sChar);
+            }
+        }
+        return true;
+    }
+}

+ 47 - 0
src/leetcode/p205/SolutionTest.java

@@ -0,0 +1,47 @@
+package leetcode.p205;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: SolutionTest
+ * @Author: 杨逸
+ * @Data:2026/3/8 16:11
+ * @Description:
+ */
+@RunWith(Parameterized.class)
+public class SolutionTest {
+    public static final Solution solution = new Solution();
+    private final String s;
+    private final String t;
+    private final boolean expected;
+
+    public SolutionTest(String s, String t, boolean expected) {
+        this.s = s;
+        this.t = t;
+        this.expected = expected;
+    }
+    @Parameterized.Parameters
+    public static Collection<Object[]> data(){
+        return Arrays.asList(new Object[][]{
+                {"egg","add",true},
+                {"f11","b23",false},
+                {"paper","title",true},
+                {"bbbaaaba","aaabbbba",false},
+                {"badc","baba",false},
+        });
+    }
+
+    @Test
+    public void isIsomorphic() {
+        boolean result = solution.isIsomorphic(s, t);
+        assertEquals(expected, result);
+    }
+}