用于查找一个字符串是否是另一个字符串的前缀的数据结构

发布于 2024-12-24 02:09:19 字数 413 浏览 0 评论 0原文

这是一道面试题:设计一个数据结构来高效地执行以下操作:boolean isPrefix(String s1, String s2)

我想我们可以创建一个 multimap,它将前缀映射到它们的字符串。例如,

strings: "aa", "ab", "abc", "ba", "ca"
multimap: "a"   -> ["aa", "ab", "abc"]
          "aa"  -> ["aa"]
          "ab"  -> ["ab", "abc"]
          "abc" -> ["abc"]
          "ba"  -> ["ba"]
          "ca"  -> ["ca"]

您会建议哪种数据结构?

This is an interview question: Design a data structure to perform the following operation efficiently: boolean isPrefix(String s1, String s2).

I guess we can create a multimap, which maps prefixes to their strings. For instance,

strings: "aa", "ab", "abc", "ba", "ca"
multimap: "a"   -> ["aa", "ab", "abc"]
          "aa"  -> ["aa"]
          "ab"  -> ["ab", "abc"]
          "abc" -> ["abc"]
          "ba"  -> ["ba"]
          "ca"  -> ["ca"]

Which data structure would you propose ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凑诗 2024-12-31 02:09:19

trie 数据结构似乎是一个显而易见的答案,但所述问题并不需要高级数据结构。简单的字符串比较就足够了,而且速度非常快。最终,如果您想验证一个字符串是否是另一个字符串的前缀,则必须比较相应位置的每个字符。没有任何数据结构可以消除逐个字符比较的需要。

话虽这么说,如果您在大量文本中搜索前缀,还有其他技术,例如Rabin-Karp 概率字符串匹配

The trie data structure would seem like an obvious answer, but the problem as stated doesn't require an advanced data structure. A simple string comparison will suffice and would be very fast. Ultimately, if you want to validate that one string is a prefix of another, you will have to compare every character at corresponding positions. No data structure eliminates the need for the character-by-character comparison.

That being said, if you're searching for the prefix in a large body of text, there are other techniques such as Rabin-Karp probablistic string matching.

孤芳又自赏 2024-12-31 02:09:19

最有效的前缀信息存储可能是 trie

在这种情况下,字符串对应于树中的节点,其中当一个字符串的节点位于树中另一个字符串的下方时,一个字符串将另一个字符串作为前缀。

The most effective storage for prefix information is probably the trie.

In this, the strings correspond to nodes in a tree where one string has another as a prefix exactly when its node is below the other in the tree.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文