Skip to content

Latest commit

 

History

History
36 lines (25 loc) · 955 Bytes

2185.md

File metadata and controls

36 lines (25 loc) · 955 Bytes

Level: Easy

Topic: Array String

Question

Return the number of strings in words that contain pref as a prefix.

Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".

Intuition

Straightforward

  • iterate the words array and compare each word with pref at pref's length

Code

Time: O(n)
Space: o(1)

public int prefixCount(String[] words, String pref) {
    int len = pref.length();
    int ans = 0;
    for (String word: words) {
        if (word.length() >= len)
            ans += word.substring(0, len).equals(pref) ? 1:0;
    }
    return ans;
}