Leetcode: Isomorphic Strings
2015-07-29 23:37
330 查看
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
Given
Given
Note:
You may assume both s and t have the same length.
注意不同的字符不能映射到同一个字符这个条件。
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> charMapping;
unordered_set<char> occupied;
for (int i = 0; i < s.size(); ++i) {
auto iter = charMapping.find(s[i]);
if (iter == charMapping.end()) {
if (occupied.find(t[i]) == occupied.end()) {
charMapping.emplace(s[i], t[i]);
occupied.emplace(t[i]);
}
else {
return false;
}
}
else {
if (t[i] != iter->second) {
return false;
}
}
}
return true;
}
};
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.
注意不同的字符不能映射到同一个字符这个条件。
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> charMapping;
unordered_set<char> occupied;
for (int i = 0; i < s.size(); ++i) {
auto iter = charMapping.find(s[i]);
if (iter == charMapping.end()) {
if (occupied.find(t[i]) == occupied.end()) {
charMapping.emplace(s[i], t[i]);
occupied.emplace(t[i]);
}
else {
return false;
}
}
else {
if (t[i] != iter->second) {
return false;
}
}
}
return true;
}
};
相关文章推荐
- c语言实现hashmap(转载)
- Ruby中Hash的11个问题解答
- Ruby简明教程之数组和Hash介绍
- 在C#中生成与PHP一样的MD5 Hash Code的方法
- js中hash和ico的关联分析
- Javascript SHA-1:Secure Hash Algorithm
- 理解php Hash函数,增强密码安全
- PHP利用hash冲突漏洞进行DDoS攻击的方法分析
- PowerShell中定义哈希散列(Hash)和调用例子
- Redis String 类型和 Hash 类型学习笔记与总结
- php操作redis中的hash和zset类型数据的方法和代码例子
- Perl 哈希Hash用法之入门教程
- perl哈希hash的常见用法介绍
- php自定义hash函数实例
- php对文件进行hash运算的方法
- php常用hash加密函数
- PHP Hash算法:Times33算法代码实例
- php的hash算法介绍
- memcache一致性hash的php实现方法
- Mysql中的Btree与Hash索引比较