Given a set of hotel reviews and a string containing “Good Words”, sort the reviews in descending order of their “Goodness Value” (number of good words in the review). Sorting should be stable: if two reviews have the same goodness value, preserve their original order.
You are expected to use a Trie for efficient good word lookup.
Input:
S ="cool_ice_wifi"R =["water_is_cool","cold_ice_drink","cool_wifi_speed"]Output:
[2,0,1]Explanation: Sorted reviews are ["cool_wifi_speed","water_is_cool","cold_ice_drink"]
A Trie allows fast lookup of good words. For each review, count how many words are in the Trie, then sort reviews by this count (goodness value), preserving original order for ties.
classSolution:
defsolve(self, A: str, B: list[str]) -> list[int]:
classTrieNode:
def__init__(self):
self.children = {}
self.is_end =FalseclassTrie:
def__init__(self):
self.root = TrieNode()
definsert(self, word: str):
node = self.root
for c in word:
if c notin node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.is_end =Truedefsearch(self, word: str) -> bool:
node = self.root
for c in word:
if c notin node.children:
returnFalse node = node.children[c]
return node.is_end
trie = Trie()
for word in A.split('_'):
trie.insert(word)
goodness = []
for idx, review in enumerate(B):
count = sum(trie.search(w) for w in review.split('_'))
goodness.append((-count, idx))
goodness.sort()
return [idx for _, idx in goodness]