给定两个字符串str1和str2 ,任务是检查两个给定的字符串是否彼此同构。
Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 map to same character in str2.
例子:
Input: str1 = “egg”, str2 = “add”
Output: Yes
Explanation:
‘e’ in str1 with ASCII value 101 is mapped to ‘a’ in str2 with ASCII value 97.
‘g’ in str1 with ASCII value 103 is mapped to ‘d’ in str2 with ASCII value 100.
Input: str1 = “eggs”, str2 = “addd”
Output: No
Hashing 方法:请参阅上一篇关于基于 Hashmap 的方法的文章。
时间复杂度: O(N)
辅助空间: O(256)
基于 ASCII 值的方法:其思想与上述方法类似。请按照以下步骤解决问题:
- 初始化两个大小为 256 的数组。
- 迭代通过给定字符串和增量索引的字符等于所述字符的ASCII值在第i个位置。
- 如果字符映射没有冲突,则打印Yes 。否则,打印No 。
下面是上述方法的实现:
C
// C Program to implement
// the above approach
#include
#include
#include
// Function to check and return if strings
// str1 and str2 are ismorphic
bool areIsomorphic(char *str1, char *str2)
{
// If the length of the strings
// are not equal
if (strlen(str1) != strlen(str2)) {
return false;
}
// Initialise two arrays
int arr1[256] = { 0 }, arr2[256] = { 0 };
// Travsersing both the strings
for (int i = 0; i < strlen(str1); i++) {
// If current characters don't map
if (arr1[(int)str1[i]]
!= arr2[(int)str2[i]]) {
return false;
}
// Increment the count of characters
// at their respective ASCII indices
arr1[(int)str1[i]]++;
arr2[(int)str2[i]]++;
}
return true;
}
// Driver Code
int main()
{
char s1[] = "aab", s2[] = "xxy";
if (areIsomorphic(s1, s2))
printf("Yes\n");
else
printf("No\n");
return 0;
}
Yes
时间复杂度: O(N)
辅助空间: O(256)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live