加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 快速的字谜解决

发布时间:2020-12-16 21:28:50 所属栏目:百科 来源:网络整理
导读:鉴于两个字符串,我想确定它们是否是彼此的字谜.这是我提出的解决方案: # output messagesdef anagram puts "Anagram!" exit enddef not_anagram puts "Not an anagram!" exitend# main methodif __FILE__ == $0 # read two strings from the command line f
鉴于两个字符串,我想确定它们是否是彼此的字谜.这是我提出的解决方案:
# output messages
def anagram
    puts "Anagram!"
    exit 
end

def not_anagram
    puts "Not an anagram!"
    exit
end

# main method
if __FILE__ == $0
   # read two strings from the command line
   first,second = gets.chomp,gets.chomp

   # special case 1
   not_anagram if first.length != second.length

   # special case 2
   anagram if first == second

   # general case
   # Two strings must have the exact same number of characters in the
   # correct case to be anagrams.
   # We can sort both strings and compare the results
   if first.chars.sort.join == second.chars.sort.join
      anagram
   else
      not_anagram
   end
end

但我认为可能有一个更好的.我分析了这个解决方案的效率,并得出:

> chars:将字符串拆分为字符数组O(n)
> sort:按字母顺序对字符串进行排序,我不知道如何在Ruby中实现排序,但我假设为O(n log n),因为这是通常最为人所知的排序效率
> join:从字符数组O(n)构建一个字符串
> ==:字符串比较本身必须检查字符串2 * O(n)的每个字符

鉴于上述情况,我将整个解决方案的效率分类为O(n log n),因为排序效率最高.有没有比O(n log n)更有效的方法呢?

解决方法

你的大O应该是O(n * lg(n))因为排序是限制功能.如果你尝试使用非常大的字谜,你会发现O(n)解决方案的性能损失高于预期.

您可以通过比较两个字符映射中的计数来执行O(n)解决方案=>人物数量.

肯定有其他解决方案具有大致相同的复杂性,但我认为你不能提出任何比O(n)更快的解决方案

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读