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.
我的解決方案:
// isIsomorphic.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<map>
#include<string>
#include<iostream>
#include<unordered_map>
using namespace std;
bool isIsomorphic(string s, string t)
{
if(s.length()!=t.length())return false;
int s_length = s.length();
int t_length = t.length();
unordered_map<char,char> stemp;
unordered_map<char,char> ttemp;
for(int i = 0;i < s_length; i++)
{
if(stemp.find(s[i]) == stemp.end() && ttemp.find(t[i]) == ttemp.end())
{
stemp[s[i]] = t[i];
ttemp[t[i]] = s[i];
}
else
{
if(stemp.find(s[i]) == stemp.end() && ttemp[t[i]]!=s[i])
{
return false;
}
else if(ttemp.find(t[i])==ttemp.end() && stemp[s[i]]!=t[i])
{
return false;
}
else if(stemp[s[i]] != t[i] && ttemp[t[i]] != s[i])
{
return false;
}
}
}
}
//
//pair<map<char,int>::iterator,bool> Insert_Pair;
//Insert_Pair = mapString.insert(map<char,int>::value_type(s[i],(int)(s[i] - t[i])));
int _tmain(int argc, _TCHAR* argv[])
{
string s = "ab";
string t = "aa";
isIsomorphic(s,t);
return 0;
}
unordered_map 簡介:
http://blog.csdn.net/gamecreating/article/details/7698719
http://blog.csdn.net/orzlzro/article/details/7099231
http://blog.csdn.net/sws9999/article/details/3081478
unordered_map,它與map的區分就是map是依照operator<比較判斷元素是不是相同,和比較元素的大小,然后選擇適合的位置插入到樹中。所以,如果對map進行遍歷(中序遍歷)的話,輸出的結果是有序的。順序就是依照operator< 定義的大小排序。而unordered_map是計算元素的Hash值,根據Hash值判斷元素是不是相同。所以,對unordered_map進行遍歷,結果是無序的。而hash則是把數據的存儲和查找消耗的時間大大下降;而代價僅僅是消耗比較多的內存。雖然在當前可利用內存愈來愈多的情況下,用空間換時間的做法是值得的。
用法的區分就是map的key需要定義operator<。而unordered_map需要定義hash_value函數并且重載operator==。對自定義的類型做key,就需要自己重載operator< 或hash_value()了。
python 的解決方案:
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
def halfIsom(s, t):
res = {}
for i in xrange(len(s)):
if s[i] not in res:
res[s[i]] = t[i]
elif res[s[i]] != t[i]:
return False
return True
return halfIsom(s, t) and halfIsom(t, s)
上一篇 【hdoj 1007】最近點對
下一篇 python 5 條件判斷和循環