[每日一题]2185.统计包含给定前缀的字符串
2185. 统计包含给定前缀的字符串 给你一个字符串数组 words 和一个字符串 pref 。返回 words 中以 pref 作为 前缀 的字符串的数目。字符串 s 的 前缀 就是 s 的任一前导连续字符串。
Solution
class Solution {
public int prefixCount(String[] words, String pref) {
int count = 0;
int len = pref.length();
for (var s : words) {
if (s.length() < len) {
continue;
}
if (s.substring(0, len).equals(pref)) {
count++;
}
}
return count;
}
}
又是暴力解,一行代码整活。。。
class Solution {
public int prefixCount(String[] words, String pref) {
return (int) Arrays.stream(words).filter(
word -> word.startsWith(pref)).count();
}
}