leetcode-205. Isomorphic Strings
2016-04-27 21:24
411 查看
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
思路:两个数组分别存各自字符出现的次数,遍历判断,当某次个数不相等时返回false,否则为true
下面用的是hash表,效率会低一些
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
思路:两个数组分别存各自字符出现的次数,遍历判断,当某次个数不相等时返回false,否则为true
下面用的是hash表,效率会低一些
class Solution { map<char,int> hashMap; public: bool isIsomorphic(string s, string t) { //思路:将字符映射成对应数字,数字从1计数,存在hash表里,最后比较两个转换后的是否一样 int lengthS = s.size(); int lengthT = t.size(); if(lengthS != lengthT) { return false; } int globalIndex = 1; //s转换 for(int i=0;i<lengthS;i++) { if(hashMap.find(s[i]) == hashMap.end()) { hashMap.insert(make_pair(s[i],globalIndex)); s[i] = globalIndex; globalIndex++; } else { s[i] = hashMap[s[i]]; } } //t转换,这个其实可以封装成函数,这冗余了先不改 hashMap.clear(); globalIndex = 1; for(int i=0;i<lengthT;i++) { if(hashMap.find(t[i]) == hashMap.end()) { hashMap.insert(make_pair(t[i],globalIndex)); t[i] = globalIndex; globalIndex++; } else { t[i] = hashMap[t[i]]; } } //判断 for(int i=0;i<lengthS;i++) { if(s[i] != t[i]) { return false; } } return true; } };
相关文章推荐
- 【BZOJ3670】[Noi2014]动物园【KMP】【fail树】
- AndroidManifest中的android:labe=""
- UVA 11997 - K Smallest Sums(多路归并)
- this指针说明(c++)
- poj 3107 Godfather(树形DP)
- 安装hbase
- 每日Scrum--No.9
- 团队项目第一阶段冲刺站立会议09
- JavaScript语法
- softmax代价函数的导数计算
- PAT-B 1009. 说反话
- 跑偏程序员自学cocos2d-x之三 场景切换
- UVA 10305 Ordering Tasks
- 安卓取服务器上面的数据
- 关于启明星系统移除apppath配置,让系统自动获取路径来设置cookie的解决方法
- JavaScript学习汇总
- 团队项目第一阶段冲刺站立会议08
- Python提取数据
- 提高代码质量:如何编写函数
- android textView加圆环 只需要加个背景就行了