Oracle 面试题:同字母异序词替换下的句子计数

79次阅读
没有评论

Given an array of words and an array of sentences, calculate how many distinct sentences can be created by replacing any word with one of its anagrams.

Note:
• Two words are said to be anagrams of each other if one can be created by rearranging the letters of the other word, using all the original letters exactly once.

Example:
wordSet = [‘listen’,‘silent’,‘it’,‘is’]
sentence =“listen it is silent”

Determine that“listen”is an anagram of“silent”. Those two words can be replaced with their anagrams. The four sentences that can be created are:
• listen it is silent
• listen it is listen
• silent it is silent
• silent it is listen

Function Description
Complete the function countSentences in the editor below.

countSentences has the following parameters:
• string wordSet[n]: an array of strings
• string sentences[m]: an array of strings (each sentence is space-separated words)

Return:
• long integer array: for each sentence, the number of distinct sentences that can be formed by replacing words with any of their anagrams from wordSet.

Constraints:
• All strings are lowercase English letters.
• 1 ≤ n, m ≤ reasonable limits for typical interview problems.
• Words appear in sentences only if they exist in wordSet (or you may assume nonexistent words contribute a factor of 1).


同字母异序词 视为同一类(按排序后的“签名”分组)。
一句话的可组合数 = 句中每个词对应分组的大小相乘(不存在则乘 1)。
因此:预处理 wordSet,按字母排序作为 key 统计频次;逐句拆词,累乘各词所在分组的计数即可。时间复杂度:预处理 O(∣wordSet∣·LlogL),每句 O(词数·LlogL)。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Oracle、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0