基本上我有两个子问题。 第一个问题是:给定 2 个字符串,确定它们是否是变位词。 二是有点难。您有 N 个字符串,必须确定它们是否是彼此的变位词。
我已经解决了第一个问题,我将在下面编写代码,但对于第二个问题我不知道。我在想可以通过从字符串数组中读取 N 个字符串,然后使用 for 序列读取每个字符串并进行比较来以某种方式做到这一点,但我不知 Prop 体怎么做。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string word1; string word2;
getline(cin,word1);
getline(cin,word2);
if(word1.length()==word2.length()){
sort(word1.begin(), word1.end());
sort(word2.begin(), word2.end());
if(word1==word2) cout<<"The words are anagrams of each other"<<endl;
else cout<<"The words are not anagrams of each other"<<endl;
}
else cout<<"The words are not the same length"<<endl;
return 0;
}
最佳答案
判断两个字符串是否是变位词非常简单,尤其是对于 ASCII 字符集。最好的方法是创建一个大小为 256 的 int 数组。遍历第一个字符串并为每个 char++ 该 int。对第二个字符串执行相同的操作并检查数组的结尾是否相同。
将其扩展到多个字符串很容易,因为 if
a is anagram of b and b is anagram of c then a is anagram of c
如果您使用更大的非 ASCII 字符集执行此操作,则使用 HashMap 而不是位集可能是个好主意。
关于c++ - 判断 N 个字符串是否是彼此的变位词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19433464/