Chapter 1 Arrays and Strings - 1.4

1.4 Write a method to decide if two strings are anagrams or not.

This "easy" problem really taught me a lesson. Firstly, I quickly came up with a somewhat smart solution:
import string
def are_anagrams(str1, str2):
    # To change a string, we have to convert it to a list first
    str1_list = [i for i in str1]
    str2_list = [i for i in str2]

    # Sort the two lists
    str1_list.sort()
    str2_list.sort()

    # Convert back to strings for comparison
    str1 = string.join(str1_list)
    str2 = string.join(str2_list)

    # Compare the sorted strings
    return str1 == str2

If we use quick sort, the solution above takes O(nlgn) running time. Andthen... I stopped!

So bad. I have seen so many problems and most of them have time complexity of O(nlgn) and cannot be improved further. So I naturally set O(nlgn) as my final goal. However, when I turned to the answer page, I found a better solution: if we sacrifice space, we can achieve O(n). The code below is my implementation based on the same thought as standard answer:

def are_anagrams2(str1, str2):
    if len(str1) != len(str2):
        return False
    
    flags = [0 for i in range(0, 256)]
    for i in range(0, len(str1)):
        index1 = ord(str1[i])
        index2 = ord(str2[i])
        # One occurrence of a letter in str1
        # makes the corresponding flag increase by one
        flags[index1]  = flags[index1] + 1

        # One occurrence of a letter in str2
        # makes the corresponding flag decrease by one
        flags[index2]  = flags[index2] - 1
    
    # If there exist a flag that is not 0, the two strings are not anagrams
    for i in range(0, 256):
        if flags[i] != 0:
            return False
    return True

I will keep it in mind: there is no perfect solution, and there always exists a better solution!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值