给定两个字符串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
哈希方法:有关基于哈希图的方法,请参阅上一篇文章。
时间复杂度: O(N)
辅助空间: O(256)
基于ASCII值的方法:该想法与上述方法类似。请按照以下步骤解决问题:
- 初始化大小为256的两个数组。
- 迭代通过给定字符串和增量索引的字符等于所述字符的ASCII值在第i个位置。
- 如果在字符映射中没有冲突,请打印“是” 。否则,打印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)