如果第一个字符串中的一个字母可以被第二个字符串中的另一个字母替换,则说2个字符串是同构的。
Example 1: string_1 = add string_2 = egg Output: True Here “a” can be replaced by “e” and “d” can be replaced by “g”. Example 2: string_1 = foo string_2 = bar Output: False Here “f” can be replaced by “b” and “o” can be replaced by, “a”, and “o” again cannot be replaced by “r”. Hence it will return false.
可以通过2个哈希图解决此问题。
我们将标记两个哈希图中元素所在的所有索引。
然后检查该索引处的两个哈希图是否相同。如果它们相同,我们将在下一个索引处进行检查。如果它们不相同,则表示我们已将该字母映射到另一个字母。因此退出循环。
在下面的输出中将给出有关实现的清晰思路。
C ++解决方案
#include<iostream> #include<string> #include<vector> using namespace std; bool check_isomorphic(string str_1, string str_2) { int hash_map_1[256]={0}; int hash_map_2[256]={0}; for(int i=0;i<str_1.length();i++) { cout<<"Step 1 i = "<<i <<" hash_map_1[str_1[i]] = "<< hash_map_1[str_1[i]]<<" hash_map_2[str_2[i]] = "<< hash_map_2[str_2[i]]<<endl; if(hash_map_1[str_1[i]]!=hash_map_2[str_2[i]]) { return false; } hash_map_1[str_1[i]] = 1; hash_map_2[str_2[i]] = 1; } return true; } int main() { string str_1 = "add"; string str_2 = "egg"; cout<<"===========Test case 1==========="<<endl; cout<<"string 1 = "<<str_1 <<" string 2 = "<<str_2<<endl; if(check_isomorphic(str_1, str_2)) cout<<"\nResult: The 2 strings are isomorphic"<<endl; else cout<<"\nResult: The 2 strings are NOT isomorphic"<<endl; str_1 = "foo"; str_2 = "bar"; cout<<"\n===========Test case 2==========="<<endl; cout<<"string 1 = "<<str_1 <<" string 2 = "<<str_2<<endl; if(check_isomorphic(str_1, str_2)) cout<<"\nResult: The 2 strings are isomorphic"<<endl; else cout<<"\nResult: The 2 strings are NOT isomorphic"<<endl; return true; }
输出:
===========Test case 1=========== string 1 = add string 2 = egg Step 1 i = 0 hash_map_1[str_1[i]] = 0 hash_map_2[str_2[i]] = 0 Step 1 i = 1 hash_map_1[str_1[i]] = 0 hash_map_2[str_2[i]] = 0 Step 1 i = 2 hash_map_1[str_1[i]] = 1 hash_map_2[str_2[i]] = 1 Result: The 2 strings are isomorphic ===========Test case 2=========== string 1 = foo string 2 = bar Step 1 i = 0 hash_map_1[str_1[i]] = 0 hash_map_2[str_2[i]] = 0 Step 1 i = 1 hash_map_1[str_1[i]] = 0 hash_map_2[str_2[i]] = 0 Step 1 i = 2 hash_map_1[str_1[i]] = 1 hash_map_2[str_2[i]] = 0 Result: The 2 strings are NOT isomorphic
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |