📌  相关文章
📜  Python程序通过重新排列单词来检查两个句子是否可以相同

📅  最后修改于: 2021-09-07 02:29:01             🧑  作者: Mango

给定两个ST吊环S1S2代表两句话,任务是检查是否可以通过重新排列任何字符串的单词来使两个句子相同。

例子:

使用sort()split()内置函数的方法:按照步骤解决问题:

  • 将字符串S1S2的单词分别存储在单独的列表中,例如list1[]list2[]
  • 按升序对两个列表进行排序。
  • 如果发现两个列表相等,则打印“是”。否则,打印“否”

下面是上述方法的实现:

Python3
# Python implementation
# of the above approach
  
# Function to check if two sentences
# can be made same by rearranging words
def ReArrangeStrings(string1, string2):
  
    # Stores the words of the
    # sentences in separate lists
    list1 = list(string1.split())
    list2 = list(string2.split())
  
    # Sort both the strings
    list1.sort()
    list2.sort()
  
    # If two lists are equal
    if(list1 == list2):
        return True
    else:
        return False
  
  
# Driver Code
  
# Input
S1 = "please select a category"
S2 = "category please a select"
  
# Function call to check if two sentences
# can be made same by rearranging words
if(ReArrangeStrings(S1, S2)):
    print("Yes")
else:
    print("No")


Python3
# Python implementation
# of the above approach
  
# Import counter function
# from collections
from collections import Counter
  
  
# Function to check if two sentences
# can be made same by rearranging words
def ReArrange(S1, S2):
  
    # Store the words of the
    # strings in separate lists
    list1 = list(S1.split())
    list2 = list(S2.split())
  
    listcounter1 = Counter(list1)
    listcounter2 = Counter(list2)
  
    # If counter of both the
    # sentences are same
    if(listcounter1 == listcounter2):
        return True
    else:
        return False
  
  
# Driver Code
  
# Input
S1 = "please select a category"
S2 = "category please a select"
  
# Function call to check if two
# sentences can be made same
# by rearranging words
if(ReArrange(S1, S2)):
    print("Yes")
else:
    print("No")


输出:
Yes

时间复杂度: O(N* M* log(N)),其中 M 是最长字符串的长度。
辅助空间: O(N)

使用Counter()和 split() 内置函数的方法:按照步骤解决问题:

  • 将字符串S1S2的单词分别存储在单独的列表中,例如list1[]list2[]
  • 使用 Counter()函数计算字符串S1S2 中出现的单词并将其存储在单独的变量中,分别说counter1counter2
  • 检查counter1是否等于counter2 。如果发现是真的,打印“是” 。否则,打印“否”

下面是上述方法的实现:

蟒蛇3

# Python implementation
# of the above approach
  
# Import counter function
# from collections
from collections import Counter
  
  
# Function to check if two sentences
# can be made same by rearranging words
def ReArrange(S1, S2):
  
    # Store the words of the
    # strings in separate lists
    list1 = list(S1.split())
    list2 = list(S2.split())
  
    listcounter1 = Counter(list1)
    listcounter2 = Counter(list2)
  
    # If counter of both the
    # sentences are same
    if(listcounter1 == listcounter2):
        return True
    else:
        return False
  
  
# Driver Code
  
# Input
S1 = "please select a category"
S2 = "category please a select"
  
# Function call to check if two
# sentences can be made same
# by rearranging words
if(ReArrange(S1, S2)):
    print("Yes")
else:
    print("No")
输出:
Yes

时间复杂度 O(N)
辅助空间: O(N)