LeetCode 刷题之205-同构字符串, Isomorphic

205. 同构字符串

难度简单 
给定两个字符串 s 和 t ,判断它们是否是同构的。

如果 s 中的字符可以按某种映射关系替换得到 t ,那么这两个字符串是同构的。

每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。

 示例 1:

输入:s = "egg", t = "add"
输出:true

示例 2:

输入:s = "foo", t = "bar"
输出:false

示例 3:

输入:s = "paper", t = "title"
输出:true

 提示: 

  • 1 <= s.length <= 5 * 104
  • t.length == s.length
  • s 和 t 由任意有效的 ASCII 字符组成
执行结果:通过
内存消耗:41.8 MB, 在所有 Java 提交中击败了5.01%的用户
通过测试用例:43 / 43
 
 1 class Solution {
 2     public boolean isIsomorphic(String s, String t) {
 3         char ch1_s, ch2_s, ch1_t, ch2_t;
 4         for (int i=0; i<s.length(); ) {
 5             ch1_s=s.charAt(i);
 6             ch1_t=t.charAt(i);
 7             int cursor_s, cursor_t;
 8             cursor_s=cursor_t=i;
 9 
10             do {
11                 cursor_s=s.indexOf(ch1_s, ++cursor_s);
12                 cursor_t=t.indexOf(ch1_t, ++cursor_t);
13                 if (cursor_s != cursor_t)
14                     return false;
15             } while(cursor_s != -1 );
16             s=s.replace(Character.toString(ch1_s), "");
17             t=t.replace(Character.toString(ch1_t), "");
18             i=0;
19         }
20         return true;
21     }
22 }

 

 
posted @ 2022-04-02 11:08  blues667  阅读(31)  评论(0)    收藏  举报