1.题目描述:
给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。
请你返回 words 中是字符串 s 前缀 的 字符串数目 。
一个字符串的 前缀 是出现在字符串开头的子字符串。子字符串 是一个字符串中的连续一段字符序列
输入:words = [“a”,“b”,“c”,“ab”,“bc”,“abc”], s = “abc”
输出:3
解释:
words 中是 s = “abc” 前缀的字符串为:
“a” ,“ab” 和 “abc” 。
所以 words 中是字符串 s 前缀的字符串数目为 3 。
2.代码块
刚开始看不懂题目,以为只要words中是以字母a开头的字符串就可以了!
private void button23_Click(object sender, EventArgs e)
{
string[] words = { "a", "b", "c", "ab", "bc", "abc" };
string s = "abc";
int num = CountPrefixes(words, s);
Console.WriteLine(num);
}
//统计是给定字符串前缀的字符串数目
public int CountPrefixes(string[] words, string s)
{
int count = 0;
for (int i = 0; i < words.Length; i++)
{
string tmp = words[i];
if (words[i].Length <= s.Length && tmp == s.Substring(0, tmp.Length))
{
count++;
}
}
return count;
}