LeetCode(205)Isomorphic Strings
来源:互联网 发布:原生js实现数据绑定 编辑:程序博客网 时间:2024/04/29 03:09
题目
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.
分析
判断给定的两个字符串是否同构,字符串字面上很容易就能看得出来;
但是怎么用算法来判断呢?
仔细分析:
e <——> a
g <——> d
g <——> d
感觉像离散数学中的双向映射。
在数据结构中可以选择map,选择unordered_map来存储字母映射关系,它的搜索性能为常量。
AC代码
class Solution {public: bool isIsomorphic(string s, string t) { if (s.size() != t.size()) return false; //求两个字符串的长度 int len = s.size(); //首先验证字符串s—>t的映射 unordered_map<char, char> um; for (int i = 0; i < len; ++i) { auto pos = um.find(s[i]); if (pos == um.end()) um.insert({ s[i], t[i] }); else{ if ((*pos).second != t[i]) return false; }//else }//for //再验证字符串t—>s的映射 um.clear(); for (int i = 0; i < len; ++i) { auto pos = um.find(t[i]); if (pos == um.end()) um.insert({ t[i], s[i] }); else{ if ((*pos).second != s[i]) return false; }//else }//for return true; }};
GitHub测试程序源码
0 0
- 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
- Isomorphic Strings - LeetCode 205
- Isomorphic Strings leetcode 205
- leetcode 205:Isomorphic Strings
- leetcode-205 Isomorphic Strings
- Isomorphic Strings(leetcode 205)
- leetcode[205]:Isomorphic Strings
- leetcode-205-Isomorphic Strings
- leetcode 205: Isomorphic Strings
- leetcode: (205) Isomorphic Strings
- [LeetCode 205] Isomorphic Strings
- Linux init进程详解
- 02 计算字符串表达式 [类似于js eval函数]
- listview加载自定义item,Baseadapter适配
- 算法学习之排序:快速排序算法
- python 函数定义
- LeetCode(205)Isomorphic Strings
- angular的$interpolate服务
- GET POST方法长度限制
- bash: rz: command not found
- PAT 1050. String Subtraction (20)
- 1051 Pop Sequence
- 使用@property
- delphi7编程技巧
- Leetcode166: Number of Islands