[leetcode] 205. Isomorphic Strings
来源:互联网 发布:淘宝拍卖房产过户 编辑:程序博客网 时间:2024/05/29 03:57
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.
解法一:
建立hash table,看s[i]是否出现过,如果没有,将t[i]的值作为s[i]的映射。如果出现过,检验t[i]是否与s[i]的映射相同。对s->t, t->s各做一次循环。
class Solution {public: bool isIsomorphic(string s, string t) { int m[256] = {0}; for(int i=0; i<s.size();++i){ if(!m[s[i]]) m[s[i]] = t[i]; else{ if (m[s[i]]!=t[i]) return false; } } int n[256] = {0}; for(int i=0; i<s.size();++i){ if(!n[t[i]]) n[t[i]] = s[i]; else{ if (n[t[i]]!=s[i]) return false; } } return true; }};
解法二:
核心在于m[s[i]] = i + 1; n[t[i]]= i + 1。
class Solution {public: bool isIsomorphic(string s, string t) { int m[256] = {0}, n[256] = {0}; for(int i=0; i<s.size();++i){ if (m[s[i]] != n[t[i]]) return false; m[s[i]] = i + 1; n[t[i]] = i + 1; } return true; }};
0 0
- 【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
- LeetCode - 205. Isomorphic Strings
- 第4条:通过私有构造器强化不可实例化的能力
- linux shell if 语句写法
- Min Stack
- ovs + dpdk版本说明
- 1087. All Roads Lead to Rome (30)
- [leetcode] 205. Isomorphic Strings
- 371. Sum of Two Integers [easy] (Python)
- 一句代码搞定 Android 图片压缩
- C语言正序输出输出一个整数的每一位
- springMVC入门项目[附入门教程]
- 关于Android AIDL使用
- SpringMVC国际化
- Erasure Code
- scroll事件研究