判别首字母缩略词
难度:
标签:
题目描述
Given an array of strings words
and a string s
, determine if s
is an acronym of words.
The string s
is considered an acronym of words
if it can be formed by concatenating the first character of each string in words
in order. For example, "ab"
can be formed from ["apple", "banana"]
, but it can't be formed from ["bear", "aardvark"]
.
Return true
if s
is an acronym of words
, and false
otherwise.
Example 1:
Input: words = ["alice","bob","charlie"], s = "abc" Output: true Explanation: The first character in the words "alice", "bob", and "charlie" are 'a', 'b', and 'c', respectively. Hence, s = "abc" is the acronym.
Example 2:
Input: words = ["an","apple"], s = "a" Output: false Explanation: The first character in the words "an" and "apple" are 'a' and 'a', respectively. The acronym formed by concatenating these characters is "aa". Hence, s = "a" is not the acronym.
Example 3:
Input: words = ["never","gonna","give","up","on","you"], s = "ngguoy" Output: true Explanation: By concatenating the first character of the words in the array, we get the string "ngguoy". Hence, s = "ngguoy" is the acronym.
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 10
1 <= s.length <= 100
words[i]
ands
consist of lowercase English letters.
代码结果
运行时间: 16 ms, 内存: 16.5 MB
/**
* Solution using Java Streams to check if a string s is an acronym of an array of words.
* The approach uses streams to map the first letter of each word and collect them into a single string.
*/
import java.util.Arrays;
import java.util.stream.Collectors;
public class AcronymCheckerStream {
public boolean isAcronym(String[] words, String s) {
// Check if the length of s is the same as the number of words
if (words.length != s.length()) return false;
// Use streams to map the first character of each word to a string
String acronym = Arrays.stream(words)
.map(word -> String.valueOf(word.charAt(0)))
.collect(Collectors.joining());
// Compare the built acronym with s
return acronym.equals(s);
}
}
解释
方法:
该题解首先检查输入字符串数组 `words` 的长度是否与字符串 `s` 的长度相等,因为只有当两者长度相同时,才有可能通过 `words` 的每个单词的第一个字符完全匹配字符串 `s`。接下来,题解通过遍历 `words`,对于每个单词,检查它的第一个字符是否与 `s` 中对应位置的字符相同。如果所有字符都匹配,则返回 `true`;否则,在发现第一个不匹配的字符时立即返回 `false`。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在题解中,检查`words`数组长度与`s`长度是否相等的逻辑是基于什么理由?
▷🦆
如果`words`中的某个字符串为空,题解中的`e[0]`表达式将如何处理?是否有可能引发错误?
▷🦆
题解在遍历`words`时,为何选择了`enumerate`函数?使用`enumerate`与直接通过索引访问有什么不同或优势?
▷🦆
当所有条件满足,为何题解中使用了`else`语句块来返回`True`?这里的`else`与常规使用有何不同?
▷