给定一个表示句子的字符串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
处理方法:按照以下步骤解决问题:
- 遍历字符串的字符。
- 使用split()将句子中的单词按空格拆分并将其存储为列表,例如lis。
- 将句子S中出现的所有回文词存储在一个列表中,比如newlis[]。
- 使用 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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live