translation
给定两个字符串s和t,决定它们是否是同构的。如果s中的元素被替换可以得到t,那么称这两个字符串是同构的。在用一个字符串的元素替换另一个字符串的元素的过程中,所有字符的顺序必须保留。没有两个字符可以被映射到相同的字符,但字符可以映射到该字符本身。例如,给定“egg”,“add”,返回真。给定“foo”,“bar”,返回假。给定“paper”,“title”,返回真。批注:你可以假设s和t有相同的长度。
Original
Given BothStrings S andT, determineifThey is isomorphic. Strings is isomorphicif the characters inchs can be replaced to GetT.all occurrences of a characterMust be replaced withAnothercharacter whilePreserving theOrder of characters. No Both charactersMay map to theSamecharacterButa characterMay map toitself. For Example,given"Egg","Add",return true. Given"foo","Bar",return false. Given"paper","title",return true. Note:you may assume both s andT has theSamelength.
Analysis
It's natural to think of a method that I want to output all the strings into a sequence of numbers:
For"paper"return"01023""foo"return"011""isomorphic"return"0123245607".
This feature is then implemented:
vector<int>Getvecorder (stringSTR) { Map<char, int>StrM;intindex =0; vector<int>Strvec; for(inti =0; I < str.size (); ++i) {Autoiter = Strm.find (Str[i]);if(iter = Strm.end ()) {Strm.insert (pair<Char,int> (str[i], index)); Strvec.push_back (index); Index + =1; }Else{Strvec.push_back (strm[str[i]); } }returnStrvec;}
Here, a map is used to hold the key-value pairs for each character and index, and the index is represented by index, starting at 0.
The final sequence of numbers is saved with vectors.
Loops through the entire string, looking for a character in the map each time, if not found, adds it and the corresponding index, and if it already exists, takes the index of that character out of the map and adds it to the vector.
With this module function, it is easy to solve the problem:
bool isIsomorphic(stringstring t) { vector<int> v_s = getVecOrder(s), v_t = getVecOrder(t); for (int0; i < v_s.size(); ++i) { ifreturnfalse; } returntrue;}
Because the length of the string is said to be equal, the length of the vector is certainly the same.
Code
classSolution { Public: vector<int>Getvecorder (stringSTR) {intLen = Str.size (); Map<char, int>StrM;intindex =0; vector<int>Strvec; for(inti =0; i < Len; ++i) {Autoiter = Strm.find (Str[i]);if(iter = Strm.end ()) {Strm.insert (pair<Char,int> (str[i], index)); Strvec.push_back (index); Index + =1; }Else{Strvec.push_back (strm[str[i]); } }returnStrvec; }BOOLIsisomorphic (stringSstringT) { vector<int>v_s = Getvecorder (s), v_t = Getvecorder (t); for(inti =0; I < v_s.size (); ++i) {if(V_s[i]! = V_t[i])return false; }return true; }};
Leetcode 205 Isomorphic Strings (homogeneous string) (string, vector, map) (*)