205.leetcode Isomorphic Strings (easy)[map结构 字符串处理]
2016-08-05 15:26
561 查看
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
return true.
Given
return false.
Given
return true.
题目想要判断两个字符串是否是同构的,同构的字符串用其中一个字符串中相应的字符替换两一个字符串中对应位置的字符可以得到与之前的字符串相同的字符串。因此解题思想是同构的字符串首先长度必须相同,用两个map分别存放每个位置的char与对应的位置值,然后遍历字符串对当前字符检查在之前的字符中位置是否一致。
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.length() != t.length()) return false;
int n = s.length();
map<char,int> h1;
map<char,int> h2;
for(int i=0;i<n;i++)
{
if(h1.count(s[i])==0 && h2.count(t[i]) == 0)
{
h1[s[i]] = i;
h2[t[i]] = i;
}else if(h1.count(s[i])!=0 && h2.count(t[i]) != 0 )
{
if(h1[s[i]] != h2[t[i]])
return false;
}else
return false;
}
return true;
}
};
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.
题目想要判断两个字符串是否是同构的,同构的字符串用其中一个字符串中相应的字符替换两一个字符串中对应位置的字符可以得到与之前的字符串相同的字符串。因此解题思想是同构的字符串首先长度必须相同,用两个map分别存放每个位置的char与对应的位置值,然后遍历字符串对当前字符检查在之前的字符中位置是否一致。
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.length() != t.length()) return false;
int n = s.length();
map<char,int> h1;
map<char,int> h2;
for(int i=0;i<n;i++)
{
if(h1.count(s[i])==0 && h2.count(t[i]) == 0)
{
h1[s[i]] = i;
h2[t[i]] = i;
}else if(h1.count(s[i])!=0 && h2.count(t[i]) != 0 )
{
if(h1[s[i]] != h2[t[i]])
return false;
}else
return false;
}
return true;
}
};
相关文章推荐
- 为什么主引导记录的内存地址是0x7C00?
- staticmethod classmethod 创建静态类
- JavaScript prototype
- Mac 安装cx_Oracle
- HDU - 3065 - 病毒侵袭持续中(AC自动机)
- 利用Apollo实现移动端消息推送
- Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xm
- less样式表
- 如何实现分享网站文章到微信朋友圈时显示指定缩略图或LOGO
- 数据结构实验之数组二:稀疏矩阵
- SUDT 2144 图结构练习——最小生成树
- socket TCP UDP
- css3实现三角形
- 判断一个数是不是回文数(Java StringBuffer)
- 神经网络文本分类案例
- socket FTP
- Sqlite 管理工具收藏
- POJ 1182 食物链
- POJ3267——The Cow Lexicon
- C语言中结构体的内存对齐问题