在 C++ 中,如何对字符串进行排序以使字谜词彼此靠近?
这确实是用 Java 实现的,因为您可以使用 Comparator 和内置方法对字符数组进行排序并比较字符串,如下所示:
public class AnagramComparator implements Comparator<String> {
public String sortChars(String s) {
char[] content = s.toCharArray();
Arrays.sort(content);
return new String(content);
}
public int compare(String s1, String s2) {
return sortChars(s1).compareTo(sortChars(s2));
}
}
但我想知道如何在 C++ 中实现这一点? 编写与上述 Java 代码中使用的内置方法等效的 C++ 绝对是一种选择。还有其他聪明的办法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最明显也是最好的方法与您在 Java 中选择的方法非常相似:实现自定义比较器。
在 C++ 中,这是小于谓词的特化:
并像这样调用它:
但是(就像您的 Java 代码一样)这是非常低效的,因为必须重复计算排序的字谜。仅计算一次(例如第一次使用时)并缓存它们会更有效。
例如,您可以在
less_than_sorted_anagram
谓词中将此缓存维护为std::map
(或将字符串映射到的类似字典)字符串)。The obvious and also the best way is quite similar to the one you chose in Java: implement a custom comparer.
In C++, that’s a specialisation of a less-than predicate:
And call it like this:
But (just like your Java code) this is quite inefficient since the sorted anagrams have to be computed repeatedly. It would be much more efficient to only compute them once (on first use, say) and cache them.
You could for instance maintain this cache inside the
less_than_sorted_anagram
predicate as astd::map<std::string, std::string>
(or a similar dictionary mapping strings to strings).两级方法:
将字符串
s
排序为排序后的字符串t
,并向map
添加一个条目代码>为m[t].push_back(s);
。那么映射的每个条目都是相互错位字符串的向量。您可以在单个平面多重映射中实现相同的逻辑,但这会更加昂贵(因为您每次都必须对字符串进行排序);或者您可以创建一个比较器,首先按字典顺序比较排序后的字符串,然后再比较实际的字符串,但这又非常昂贵。
A two-level approach:
Sort the the string
s
into a sorted stringt
, and add an entry to amap<string, vector<string>
asm[t].push_back(s);
. Then each entry of the map is a vector of mutually anagrammatic strings.You could implement the same logic in a single, flat multimap, but that would be far more expensive (since you'd have to sort the string each time); or you could make a comparator that lexicographically compares the sorted string first and the actual string second, but again that's very expensive.