leetcode 205. Isomorphic Strings-字符匹配|哈希表
来源:互联网 发布:php中文手册 下载 编辑:程序博客网 时间:2024/06/06 02:50
原题链接:205. Isomorphic Strings
30 / 30 test cases passed. Runtime: 64 ms Your runtime beats 75.77% of pythonsubmissions.
【思路-Java、Python】
需要用到一个 HashMap数据结构, map 中存储这样一对映射:用 s 中的每个字符作为 map 的 key, t 中的每个字符作为 map 的 value。依次遍历:
1. 如果 map 中未包含了 key,将 key 和 value 对存入 map 中。当然要保证存入的 value 之前在 t 中未出现过, 否则可能导致 s = "abc", t = "aaa"也返回 true,那么就需要一个 HashSet
2. 如果 map 中包含了 key,那么取出对应的对应的 value,如果该 value 和 t 中对应位置的 char 进行对比,如果不相等,那么返回 false
public boolean isIsomorphic(String s, String t) { HashSet<Character> set = new HashSet<Character>(); HashMap<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)); if (!set.add(t.charAt(i))) return false; //为了防止类似 s = "abc", t = "aaa"发生 } else { if (map.get(s.charAt(i)) != t.charAt(i)) return false; } } return true; }
30 / 30 test cases passed. Runtime: 25 ms Your runtime beats 58.39% of javasubmissions.
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) != len(t) : return False dict={} for i in range(len(s)) : if dict.has_key(s[i]) : if dict[s[i]] != t[i] : return False else : if t[i] in dict.values() : return False dict[s[i]] = t[i] return True
30 / 30 test cases passed. Runtime: 64 ms Your runtime beats 75.77% of pythonsubmissions.
用一个 zip 函数
class Solution(object): def isIsomorphic(self, s, t): """ :type s: str :type t: str :rtype: bool return len(set(zip(s,t)))==len(set(s)) and len(set(zip(s,t)))==len(set(t)) #下面的这个 return 也是可以的 #return len(set(zip(s,t)))==len(set(s)) and len(set(s))==len(set(t))
30 / 30 test cases passed. Runtime: 64 ms Your runtime beats 75.77% of pythonsubmissions.
1 0
- leetcode 205. Isomorphic Strings-字符匹配|哈希表
- 【LeetCode】205.Isomorphic Strings
- [leetcode] 205.Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings LeetCode
- 【LeetCode】205. Isomorphic Strings
- LeetCode *** 205. Isomorphic Strings
- leetcode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- leetcode-205. Isomorphic Strings
- LeetCode-205.Isomorphic Strings
- leetcode 205. Isomorphic Strings
- [leetcode] 205. Isomorphic Strings
- 205.[Leetcode]Isomorphic Strings
- leetcode 205. Isomorphic Strings
- 【leetcode】205. Isomorphic Strings
- [Leetcode]205. Isomorphic Strings
- 如何选择开源项目?
- 【图解HTTP笔记】第五章 与HTTP协作的Web服务器
- _itoa atoi、atof、itoa、itow _itoa_s 类型转换使用说明
- Flex实现环绕布局
- 教你如何正确反编译apk
- leetcode 205. Isomorphic Strings-字符匹配|哈希表
- 专题三 Problem A
- JDK环境变量配置
- MySQL 数据库性能优化之表结构优化
- java--Map集合常见遍历格式代码
- 数字图像处理之一 对图像进行傅立叶变换
- cocos环境配置和打包apk
- 从源码理解Stack.java
- 内存管理---创建 销毁slab