给定一个表示句子的字符串S ,任务是按排序顺序对句子中存在的所有回文词重新排序。
例子:
Input: S = “Please refer to the madam to know the level”
Output: Please level to the madam to know the refer
Explanation: Here “refer”, “madam”, “level” are the palindromic words. Sorting them generates the sequence {“level”, “madam”, “refer”}.
Input: S = “refer to dad”
Output: dad to refer
方法:请按照以下步骤解决问题:
- 遍历字符串的字符。
- 用lis分隔句子中的单词,并使用split()将它们分隔成一个列表。
- newlis []说,将句子S中存在的所有回文词存储在一个列表中。
- 使用sort()函数对列表newlis []进行排序。
- 初始化一个指针,说j = 0 。
- 遍历列表LIS和替换全部由1 newlis [J]和增量j中的回文词。
- 打印更新的句子
下面是上述方法的实现:
Python3
# Python implementation of above program
# Function to check if a
# string is a palindrome or not
def palindrome(string):
if(string == string[::-1]):
return True
else:
return False
# Function to print the updated sentence
def printSortedPalindromes(sentence):
# Stores palindromic words
newlist = []
# Stores the words split by spaces
lis = list(sentence.split())
# Traversing the list
for i in lis:
# If current word is palindrome
if(palindrome(i)):
# Update newlist
newlist.append(i)
# Sort the words in newlist
newlist.sort()
# Pointer to iterate newlis
j = 0
# Traverse the list
for i in range(len(lis)):
# If current word is palindrome
if(palindrome(lis[i])):
# Replacing word with
# current word in newlist
lis[i] = newlist[j]
# Increment j by 1
j = j + 1
# Print the updated sentence
for i in lis:
print(i, end =" ")
# Driver Code
sentence = "please refer to the madam to know the level"
printSortedPalindromes(sentence)
输出:
please level to the madam to know the refer
时间复杂度: O(N * logN)
辅助空间: O(N)