number-of-matching-subsequences 满足要求的子串个数

给定一个字符串S 和一个单词字典 words,问, words中一共有多少个单词words[i]是字符串S的子序列?
注意, 子序列不同于子串, 子序列不要求连续.

number-of-matching-subsequences

样例

样例 1:

输入: S = "abcde", words = ["a", "bb", "acd", "ace"]
输出: 3
解释: words内有三个单词是S的子串: "a", "acd", "ace".

样例 2:

输入: S = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
输出: 2

思路1

遍历数组得到 target 与 s 进行对比,在 s 中找到 target 的每个字符的下表索引,如果为 -1 证明不存在,则不是 s 的子串。

思路2

遍历数组得到 target 与 s 进行对比,设置 index 为 target 索引, i 为 s 的索引,
if (target.charAt(index) == s.charAt(i)) {
		index++;
		} 
最后判断 index == target.length 如果相等是子串,如果不相等就不是子串。

public class Solution {
 
     /**
     * @param s:     a string
     * @param words: a dictionary of words
     * @return: the number of words[i] that is a subsequence of s
     */
    public int numMatchingSubseq(String s, String[] words) {
        // Write your code here
        if (words == null || words.length == 0) {
            return 0;
        }
        int result = 0;
        for (String item : words) {
            if (isMatching( item,s)) {
                result++;
            }
        }
        return result;
    }

    private boolean isMatching(String target, String s) {
        int temp = 0;
        for (int i = 0; i < target.length(); i++) {
            int indexOf = s.indexOf(target.charAt(i), temp);
            if (indexOf == -1) {
                return false;
            }
            temp = indexOf+1;
        }
        return true;
    }
}

public class Solution{
     public int numMatchingSubseq(String S, String[] words) {
        int result = 0;
        for (String target : words) {
            if (isMatching(target, S)) {
                result++;
            }
        }
        return result;
    }

    private boolean isMatching(String target, String s) {
        int index = 0;
        int i = 0;
        while (index < target.length() && i < s.length()) {
            if (target.charAt(index) == s.charAt(i)) {
                index++;
            }
            i++;
        }
        return index == target.length();
    }

}

Github https://github.com/xingfu0809/Java-LintCode

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值