且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C ++检查两个字符串是否为字谜

更新时间:2023-11-28 19:21:10

我很懒,所以我将使用标准库功能对两个字符串进行排序,然后进行比较:

I am lazy, so I would use standard library functionality to sort both strings and then compare them:

#include <string>
#include <algorithm>

bool is_anagram(std::string s1, std::string s2)
{
  std::sort(s1.begin(), s1.end());
  std::sort(s2.begin(), s2.end());
  return s1 == s2;
}

一个小的优化可能是检查字符串的大小是否相同在排序之前。

A small optimization could be to check that the sizes of the strings are the same before sorting.

但是,如果该算法被证明是瓶颈,我将暂时摆脱一些惰性并将其与简单的计数解决方案进行比较:

But if this algorithm proved to be a bottle-neck, I would temporarily shed some of my laziness and compare it against a simple counting solution:


  1. 比较字符串长度

  2. 实例化计数图, std :: unordered_map< char,unsigned int&gt ; m

  3. s1 上循环,增加每个 char的计数

  4. s2 上循环,减少每个 char $ c的计数$ c>,然后检查计数是否为 0

  1. Compare string lengths
  2. Instantiate a count map, std::unordered_map<char, unsigned int> m
  3. Loop over s1, incrementing the count for each char.
  4. Loop over s2, decrementing the count for each char, then check that the count is 0