【问题标题】:Find if N strings are anagrams of each other查找 N 个字符串是否是彼此的字谜
【发布时间】:2013-10-26 08:11:14
【问题描述】:

基本上我有 2 个子问题。 第一个问题是:给定 2 个字符串,确定它们是否是字谜。 二是有点难。您有 N 个字符串,必须确定它们是否是彼此的字谜。

我已经解决了第一个问题,我将在下面编写代码,但对于第二个我不知道。我在想有可能通过从字符串数组中读取 N 个字符串来以某种方式做到这一点,然后使用 for 序列来读取每个字符串并进行比较,但我不知道该怎么做。

#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;
}

【问题讨论】:

  • 如果string1string2string3 的字谜,string2string3 肯定是彼此的字谜
  • 哦,是的。对此感到抱歉。我迷失了所有的东西。即使是这样。我不知道如何读取字符串数组。我搜索的所有内容都使用指针,我还没有学习。
  • @DragoşPaulMarinescu 对要检查的字符串进行排序效率极低,没有必要检查我的答案

标签: c++ string anagram


【解决方案1】:

查找两个字符串是否是字谜非常简单,尤其是对于 ASCII 字符集。最好的方法是创建一个大小为 256 的 int 数组。遍历第一个字符串并为每个 char ++ 找到该 int。对第二个字符串做同样的事情,并检查数组的结尾是否相同。

将其扩展到多个字符串很容易,因为如果

a 是 b 的字谜,b 是 c 的字谜,那么 a 是 c 的字谜

如果您使用较大的非 ASCII 字符集执行此操作,则使用哈希图而不是位集可能是个好主意。

【讨论】:

  • 我将在今天晚些时候尝试您的解决方案。首先,如果可能的话,我想根据我已经为第一个解决方案编写的代码来解决它。将您的解决方案视为“挑战”会很高兴。
  • @DragoşPaulMarinescu IMO 这很简单,如果你真的编写了自己的排序,你的解决方案实际上需要更多的努力,我不想只给你代码,但我用了大约 10 行的代码,所以它并不难
【解决方案2】:

如果 X 是 Y 和 Z 的字谜,那么 Y 和 Z 也是字谜

所以,简单地重复你的逻辑,最简单的方法:-

std::vector<std::string> words; //Use a vector
size_t i;
std::string word1,word2;
//Get words from standard input
std::copy(std::istream_iterator<std::string> (std::cin),
          std::istream_iterator<std::string>(),
          std::back_inserter(words));

word1=words[0]; //Check anagram with first word
sort(word1.begin(), word1.end());
for(i=1; i<words.size();i++)
{
    word2=words[i];
    sort(word2.begin(), word2.end());
    if(word2!=word1)
       break;
}

if(i==words.size())
    std::cout<<"All Anagrams !";

【讨论】:

  • 当我写 std::vector<:string> 单词时;编译器给出一个错误,说“命名空间 std 没有成员“向量”“我以前没有真正使用过向量,所以这对我来说是一个全新的世界。很抱歉遇到一个菜鸟:(
  • @DragoşPaulMarinescu 您需要包含正确的标题请参阅Here
  • 糟糕,忘了#include
  • 尝试在 Visual Studio 中使用代码,但出现此错误:puu.sh/4Spdn.png
  • @DragoşPaulMarinescu #include&lt;string&gt; 在你问如何退出从控制台输入单词之前,它的Ctrl+Z 或简单的F6,这些标志着流的结束。
猜你喜欢
  • 2011-05-13
  • 2016-07-10
  • 2011-12-12
  • 2016-02-16
  • 1970-01-01
  • 2016-04-07
  • 2021-10-10
相关资源
最近更新 更多