<分区>
我有这个想法(使用 C 语言)来检查两个由 ASCII 字母组成的字符串是否是彼此的变位词:
检查字符串的长度是否相同。
检查两个字符串的所有字符的 ASCII 值之和是否相同。
检查两个字符串的所有字符的 ASCII 值的乘积是否相同。
我相信如果这三个都是正确的,那么这些字符串一定是彼此的变位词。然而,我无法证明。有人可以帮我证明或反驳这行得通吗?
谢谢!
<分区>
我有这个想法(使用 C 语言)来检查两个由 ASCII 字母组成的字符串是否是彼此的变位词:
检查字符串的长度是否相同。
检查两个字符串的所有字符的 ASCII 值之和是否相同。
检查两个字符串的所有字符的 ASCII 值的乘积是否相同。
我相信如果这三个都是正确的,那么这些字符串一定是彼此的变位词。然而,我无法证明。有人可以帮我证明或反驳这行得通吗?
谢谢!
最佳答案
我编写了一个快速程序来暴力搜索冲突,发现这种方法并非总是有效。字符串 ABFN 和 AAHM 具有相同的 ASCII 和和乘积,但不是彼此的变位词。它们的 ASCII 码和为 279,ASCII 码积为 23,423,400。
还有比这更多的冲突。我的程序搜索了所有长度为 4 的字符串,发现了 11,737 个冲突。
作为引用,这里是 C++ 源代码:
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
int main() {
/* Sparse 2D table where used[sum][prod] is either nothing or is a string
* whose characters sum to "sum" and whose product is "prod".
*/
map<int, map<int, string> > used;
/* List of all usable characters in the string. */
vector<char> usable;
for (char ch = 'A'; ch <= 'Z'; ch++) {
usable.push_back(ch);
}
for (char ch = 'a'; ch <= 'z'; ch++) {
usable.push_back(ch);
}
/* Brute-force search over all possible length-four strings. To avoid
* iterating over anagrams, the search only explores strings whose letters
* are in increasing ASCII order.
*/
for (int a = 0; a < usable.size(); a++) {
for (int b = a; b < usable.size(); b++) {
for (int c = b; c < usable.size(); c++) {
for (int d = c; d < usable.size(); d++) {
/* Compute the sum and product. */
int sum = usable[a] + usable[b] + usable[c] + usable[d];
int prod = usable[a] * usable[b] * usable[c] * usable[d];
/* See if we have already seen this. */
if (used.count(sum) &&
used[sum].count(prod)) {
cout << "Conflict found: " << usable[a] << usable[b] << usable[c] << usable[d] << " conflicts with " << used[sum][prod] << endl;
}
/* Update the table. */
used[sum][prod] = string() + usable[a] + usable[b] + usable[c] + usable[d];
}
}
}
}
}
希望这对您有所帮助!
关于c - 一种确定两个字符串是否是彼此的变位词的可能算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14739186/