代码随想录day8-统计字符数组中是子串前缀的个数

给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。

请你返回 words 中是字符串 s 前缀 的 字符串数目 。

一个字符串的 前缀 是出现在字符串开头的子字符串。子字符串 是一个字符串中的连续一段字符序列。

示例 1:

输入:words = ["a","b","c","ab","bc","abc"], s = "abc"
输出:3
解释:
words 中是 s = "abc" 前缀的字符串为:
"a" ,"ab" 和 "abc" 。
所以 words 中是字符串 s 前缀的字符串数目为 3 。

示例 2:

输入:words = ["a","a"], s = "aa"
输出:2
解释:
两个字符串都是 s 的前缀。
注意,相同的字符串可能在 words 中出现多次,它们应该被计数多次。

 思路1:

把字符数组遍历,不断与子串匹配。

使用startsWith()方法进行匹配

思路2:

1.遍历字符数组,取出每个字符串

2.循环判断每个字符串字符与子串字符

 



思路1
class Solution {
    public int countPrefixes(String[] words, String s) {
        int count = 0;
        for (String word : words) {
            if (s.startsWith(word)) {
                count++;
            }
        }
        return count;
    }
}


思路2
class Solution {
    public int countPrefixes(String[] words, String s) {
        int count = 0;
        for (String word : words) {
            if (isPrefix(word, s)) {
                count++;
            }
        }
        return count;
    }

    private boolean isPrefix(String word, String s) {
        int wordLen = word.length();
        int sLen = s.length();
        if (wordLen > sLen) {
            return false;
        }
        for (int i = 0; i < wordLen; i++) {
            if (word.charAt(i) != s.charAt(i)) {
                return false;
            }
        }
        return true;
    }
}

你可能感兴趣的:(javascript,开发语言,ecmascript)