当前位置: 面试刷题>> 最长单词 (经典算法题500道)
**题目描述**:
给定一个字符串数组(单词列表),请编写一个函数来找出并返回这些单词中最长的单词。如果有多个最长单词,则返回它们中的任意一个。假设单词由小写字母组成,并且数组中的单词长度各不相同。
**示例**:
输入:`["code", "classroom", "apple", "banana"]`
输出:`"classroom"`
**PHP 代码示例**:
```php
function longestWord($words) {
$longest = '';
foreach ($words as $word) {
if (strlen($word) > strlen($longest)) {
$longest = $word;
}
}
return $longest;
}
// 测试代码
$words = ["code", "classroom", "apple", "banana"];
echo longestWord($words); // 输出:"classroom"
```
**Python 代码示例**:
```python
def longest_word(words):
return max(words, key=len)
# 测试代码
words = ["code", "classroom", "apple", "banana"]
print(longest_word(words)) # 输出:"classroom"
```
**JavaScript 代码示例**:
```javascript
function longestWord(words) {
let longest = '';
for (let word of words) {
if (word.length > longest.length) {
longest = word;
}
}
return longest;
}
// 测试代码
const words = ["code", "classroom", "apple", "banana"];
console.log(longestWord(words)); // 输出:"classroom"
```
**码小课相关内容分享**:
在码小课网站上,你可以找到更多关于算法和数据结构的深入解析,包括如何高效地处理字符串、数组等数据结构,以及如何编写清晰、可维护的代码。通过实际项目案例和理论知识的结合,码小课致力于帮助学员提升编程能力,解决复杂问题。