【发布时间】:2021-04-16 01:33:08
【问题描述】:
我只是在处理一些关于代码战的挑战。这个特别是关于编写一个函数来确定两个单词是否是字谜 - 这意味着它们包含相同的字母,可能只是乱序。
我对 C++ 很陌生,所以我可能忽略了一些非常基本的东西。这是我编写的代码,当我运行它时,主要使用两个字符串“orang”和“apple”测试 anagram 函数,程序输出 1(true),这意味着它说这两个词不是 anagrams。如果我尝试“橙色”和“苹果”,它会输出正确的 0(false)。基本上,它只是根据单词的长度而不是它们的单个字母数进行比较。
这是我的代码:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
bool isAnagram(std::string test, std::string original){
//your code here
map<char, int> freqTest;
map<char, int> freqOrig;
for(int i = 0; i < test.length(); i++) {
char c = tolower(test[i]);
freqTest[c]++;
}
for(int i = 0; i < original.length(); i++) {
char c = tolower(test[i]);
freqOrig[c]++;
}
return freqTest == freqOrig;
}
// Main function
int main()
{
string str1 = "orang";
string str2 = "apple";
cout<<isAnagram(str1, str2)<<endl;
}
【问题讨论】:
-
你打错了:你可以通过创建一个函数来创建频率图来分解你的代码,
return compute_frequency(test) == compute_frequency(original);问题可能比你使用test两次更容易发现。