<LeetCode OJ> 205. Isomorphic Strings
来源:互联网 发布:优化电脑最好的软件 编辑:程序博客网 时间:2024/05/16 13:03
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.
分析:
问题就出在有相同字符的地方,利用哈希map建立字符与位置的关系,如果字符重复的话,位置会变。
举例:
Given "egg", "add", return true.
1,先压入哈希map中得到每个字符及其对应的位置,011,011,
2,接着判断每个字符的位置是否一样011=011,所以true
Given "foo", "bar", return false.
1,压入哈希map得到位置序列,011,012
2,判断位置是否相等011!=012,所以false
class Solution {public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; unordered_map<char,int> mapsing,mapting; for(int i=0;i<s.size();i++) { mapsing[s[i]]=i; mapting[t[i]]=i; } for(int i=0;i<s.size();i++) { if(mapsing[s[i]]!=mapting[t[i]]) return false; } return true; }};
优化一下:更加耗时了,不解中......
class Solution {public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; unordered_map<char,int> mapsing,mapting; for(int i=0;i<s.size();i++) { if(mapsing[s[i]]!=mapting[t[i]]) return false; mapsing[s[i]]=i+1;//这里之所以+1,是因为防止和初始值0相巧合,比如aa和ab mapting[t[i]]=i+1; } return true; }};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50463166
原作者博客:http://blog.csdn.net/ebowtang
- <LeetCode OJ> 205. Isomorphic Strings
- LeetCode OJ Isomorphic Strings
- LeetCode OJ 205 Isomorphic Strings
- 【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
- 机器学习系列(1)_逻辑回归初步
- Android 线程 thread的实现方法
- Ⅰ.18.2 如何实现Data-Driven Testing
- couldn't setup local SOCKS5 proxy on port 7777: Address already in use: JVM_Bind
- Android四大组件之Service详解
- <LeetCode OJ> 205. Isomorphic Strings
- 【d3.js教程12】地图
- java环形打印二维数组
- 不重复随机数生成
- 机器学习系列(2)_从初等数学视角解读逻辑回归
- spring整合hibernate时lazy加载失败问题
- linux su和sudo命令的区别
- iOS延迟执行的三种方法
- Ⅰ.18.3 如何在AUT中使用测试数据