205. Isomorphic Strings
来源:互联网 发布:趣味性软件使用教程 编辑:程序博客网 时间:2024/05/01 10:50
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,时间复杂度O(nlgn)。
class Solution {public: bool isIsomorphic(string s, string t) { /* if(s.length() != t.length()) return false; map<char, char> mp1; map<char, char> mp2; for(int i=0; i<s.length(); ++i){ auto it1 = mp1.insert(make_pair(s[i], t[i])); if(!it1.second){ if(it1.first->second != t[i]) return false; } auto it2 = mp2.insert(make_pair(t[i], s[i])); if(!it2.second){ if(it2.first->second != s[i]) return false; } } return true;*/};
解法二:使用unordered_map,时间复杂度O(n):
class Solution {public: bool isIsomorphic(string s, string t) { if(s.length() != t.length()) return false; unordered_map<char, char> umap1; unordered_map<char, char> umap2; for(int i=0; i<s.length(); ++i){ auto it1 = umap1.insert(make_pair(s[i], t[i])); if(!it1.second){ if(it1.first->second != t[i]) return false; } auto it2 = umap2.insert(make_pair(t[i], s[i])); if(!it2.second){ if(it2.first->second != s[i]) return false; } }};
别人的解法:),也是O(n):
class Solution {public: bool isIsomorphic(string s, string t) { int m1[256] = {0}, m2[256] = {0}; for(int i=0; i<s.length(); ++i) { if(m1[s[i]] != m2[t[i]]) return false; m1[s[i]] = i + 1; m2[t[i]] = i + 1; } return true; }};
0 0
- 205. Isomorphic Strings
- 【LeetCode】205.Isomorphic Strings
- [leetcode] 205.Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings LeetCode
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 205. Isomorphic Strings
- 【LeetCode】205. Isomorphic Strings
- LeetCode *** 205. Isomorphic Strings
- leetcode 205. Isomorphic Strings
- LeetCode 205. Isomorphic Strings
- 205. Isomorphic Strings
- 历届试题 神奇算式 (全排列)
- Linux内核分析实验4——系统调用
- Cin输入流不定数目输入整数结束问题
- 《剑指Offer》递归和循环——斐波那契数列
- HAProxy+Keepalived的配置(二)(及重要问题说明)
- 205. Isomorphic Strings
- java利用url实现网页内容的抓取
- 设计模式----装饰模式(C++实现)
- HTML5学习之摄像头拍照组件的封装
- 1
- 【设计模式】整洁代码
- 34. Search for a Range
- imx6q内核定时器实现led闪烁
- WEB-AJAX和JQuery篇