Mon*_*rlo 4 python string python-2.7
我需要能够辨别出一个任意长度的字符串,大于1(并且只是小写),在基本字符串或模板字符串中是否具有相同的字符集.
例如,取字符串"aabc":"azbc"和"aaabc"将为false,而"acba"将为true.
有没有一种快速的方法在python中执行此操作而不跟踪第一个字符串的所有排列,然后将其与测试字符串进行比较?
Dav*_*son 12
对两个字符串进行排序,然后比较它们:
sorted(str1) == sorted(str2)
Run Code Online (Sandbox Code Playgroud)
如果字符串的长度可能不同,您可能需要首先确保它们节省时间:
len(str1) == len(str2) and sorted(str1) == sorted(str2)
Run Code Online (Sandbox Code Playgroud)
这是O(n)解决方案
from collections import Counter
Counter(str1) == Counter(str2)
Run Code Online (Sandbox Code Playgroud)
但是O(n * log n)使用的解决方案sorted对于合理的值来说可能更快n
| 归档时间: |
|
| 查看次数: |
14932 次 |
| 最近记录: |