返回介绍

solution / 2200-2299 / 2255.Count Prefixes of a Given String / README_EN

发布于 2024-06-17 01:03:08 字数 3521 浏览 0 评论 0 收藏 0

2255. Count Prefixes of a Given String

中文文档

Description

You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.

Return _the number of strings in_ words _that are a prefix of_ s.

A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation:
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.

Example 2:

Input: words = ["a","a"], s = "aa"
Output: 2
Explanation:
Both of the strings are a prefix of s. 
Note that the same string can occur multiple times in words, and it should be counted each time.

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, s.length <= 10
  • words[i] and s consist of lowercase English letters only.

Solutions

Solution 1: Traversal Counting

We directly traverse the array words, and for each string w, we check if s starts with w as a prefix. If it does, we increment the answer by one.

After the traversal, we return the answer.

The time complexity is $O(m \times n)$, where $m$ and $n$ are the lengths of the array words and the string s, respectively. The space complexity is $O(1)$.

class Solution:
  def countPrefixes(self, words: List[str], s: str) -> int:
    return sum(s.startswith(w) for w in words)
class Solution {
  public int countPrefixes(String[] words, String s) {
    int ans = 0;
    for (String w : words) {
      if (s.startsWith(w)) {
        ++ans;
      }
    }
    return ans;
  }
}
class Solution {
public:
  int countPrefixes(vector<string>& words, string s) {
    int ans = 0;
    for (auto& w : words) {
      ans += s.starts_with(w);
    }
    return ans;
  }
};
func countPrefixes(words []string, s string) (ans int) {
  for _, w := range words {
    if strings.HasPrefix(s, w) {
      ans++
    }
  }
  return
}
function countPrefixes(words: string[], s: string): number {
  return words.filter(w => s.startsWith(w)).length;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文