Leetcode 2828. Check if a String Is an Acronym of Words
You are given a list of strings words
and a string s
. A string s
is considered an acronym of the list words
if it can be formed by concatenating the first character of each string in words
in order. For example, the list ["alice", "bob", "charlie"]
generates the acronym “abc”.
Write a function isAcronym(List<String> words, String s)
which returns true
if s
is an acronym of words
, and false
otherwise.
words = ["alice", "bob", "charlie"]
s = "abc"
Output: true
words = ["apple", "banana", "carrot"]
s = "ab"
Output: false
words = ["dog", "elephant", "frog"]
s = "def"
Output: true
words
will have at least one character.1 <= words.length <= 100
1 <= s.length <= 100
["alice", "bob", "charlie"]
?
s
is not equal to the number of strings in words
, return false
.words
, extract the first character and build the expected acronym. Compare it with s
.true
; otherwise, return false
.import java.util.List;
public class Solution {
public static boolean isAcronym(List<String> words, String s) {
// If the length of the 's' is not equal to the number of words, it cannot be an acronym.
if (words.size() != s.length()) {
return false;
}
// Initialize the acronym string.
StringBuilder acronym = new StringBuilder();
// Build the acronym using the first character of each word.
for (String word : words) {
acronym.append(word.charAt(0));
}
// Compare the built acronym to the given string `s`.
return acronym.toString().equals(s);
}
public static void main(String[] args) {
List<String> words1 = List.of("alice", "bob", "charlie");
String s1 = "abc";
System.out.println(isAcronym(words1, s1)); // Should return true
List<String> words2 = List.of("apple", "banana", "carrot");
String s2 = "ab";
System.out.println(isAcronym(words2, s2)); // Should return false
List<String> words3 = List.of("dog", "elephant", "frog");
String s3 = "def";
System.out.println(isAcronym(words3, s3)); // Should return true
}
}
n
is the number of strings in the words
list. We take the first character from each string once.(Note: If we are storing the acronym in a StringBuilder, and given the constraints, this is efficient and within acceptable limits.)
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?