当前位置: 面试刷题>> 拼字游戏 (经典算法题500道)
### 题目描述补充
**题目:拼字游戏**
在一个拼字游戏中,玩家需要利用给定的字母来组成尽可能多的有效英文单词。这些给定的字母可以重复使用,但每个单词中每个字母最多只能使用一次。为了简化问题,我们假设存在一个已知的单词列表(例如,从英文词典中获取的),游戏的目标是找出并输出所有可以使用给定字母组成的单词。
**输入**:
1. 一个字符串,包含所有可用的字母(不区分大小写,可包含重复字母)。
2. 一个单词列表(集合),包含所有可能的英文单词。
**输出**:
- 一个列表,包含所有可以由给定字母组成的单词(不区分大小写,单词列表中重复的单词只输出一次)。
### 示例
**输入**:
- 可用字母:`abcde`
- 单词列表:`["apple", "bat", "cat", "bed", "bee", "tea", "each"]`
**输出**:
- `["bat", "cat", "bed", "bee", "tea"]`
### PHP 示例代码
```php
$count) {
if (!isset($letterCounts[$char]) || $letterCounts[$char] < $count) {
$isValid = false;
break;
}
}
if ($isValid) {
$result[] = $word;
}
}
// Remove duplicates
$result = array_unique($result);
return $result;
}
// Example usage
$letters = "abcde";
$wordList = ["apple", "bat", "cat", "bed", "bee", "tea", "each"];
$result = findWords($letters, $wordList);
print_r($result);
?>
```
### Python 示例代码
```python
def find_words(letters, word_list):
letters = letters.lower()
letter_counts = {}
for char in letters:
letter_counts[char] = letter_counts.get(char, 0) + 1
result = []
for word in word_list:
word = word.lower()
word_counts = {}
for char in word:
word_counts[char] = word_counts.get(char, 0) + 1
if all(word_counts[char] <= letter_counts.get(char, 0) for char in word_counts):
result.append(word)
# Remove duplicates
return list(set(result))
# Example usage
letters = "abcde"
word_list = ["apple", "bat", "cat", "bed", "bee", "tea", "each"]
result = find_words(letters, word_list)
print(result)
```
### JavaScript 示例代码
```javascript
function findWords(letters, wordList) {
letters = letters.toLowerCase().split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
const result = [];
for (const word of wordList) {
const wordLower = word.toLowerCase();
const wordCounts = wordLower.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
let isValid = true;
for (const char in wordCounts) {
if (!letters[char] || letters[char] < wordCounts[char]) {
isValid = false;
break;
}
}
if (isValid) {
result.push(word);
}
}
// Remove duplicates
return [...new Set(result)];
}
// Example usage
const letters = "abcde";
const wordList = ["apple", "bat", "cat", "bed", "bee", "tea", "each"];
const result = findWords(letters, wordList);
console.log(result);
```
**码小课网站中有更多相关内容分享给大家学习**,包括但不限于算法设计、数据结构、编程技巧等,欢迎大家访问学习。