algoadvance

Leetcode 2828. Check if a String Is an Acronym of Words

Problem Statement

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.


Example:

  1. Input:
    • words = ["alice", "bob", "charlie"]
    • s = "abc" Output: true
  2. Input:
    • words = ["apple", "banana", "carrot"]
    • s = "ab" Output: false
  3. Input:
    • words = ["dog", "elephant", "frog"]
    • s = "def" Output: true

Constraints:

Clarifying Questions

  1. Case Sensitivity: Should the acronym matching be case-sensitive? For example, should “AbC” match ["alice", "bob", "charlie"]?
    • Assume case-insensitivity unless stated otherwise.
  2. Punctuation and Special Characters: Are there any special characters or punctuation in the strings?
    • Assume no special characters, all inputs are simple lowercase alphabetic strings by default.

Strategy

  1. Initial Check: If the length of s is not equal to the number of strings in words, return false.
  2. Iterate and Compare: For each string in words, extract the first character and build the expected acronym. Compare it with s.
  3. Result: If all characters match, return true; otherwise, return false.

Code

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
    }
}

Time Complexity

(Note: If we are storing the acronym in a StringBuilder, and given the constraints, this is efficient and within acceptable limits.)

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI