发现在一组字符使用catch出现特定字符串的数 [英] Find number of occurrences of a particular string within a group of characters WITH A CATCH

查看:127
本文介绍了发现在一组字符使用catch出现特定字符串的数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何计算在一组字符出现的特定字符串的数目。美中不足的是,在字符串中的字母不需要是相邻的,但必须出现在顺序。

I'm trying to figure out how to calculate the number of occurrences of a particular string within a group of characters. The catch is that the letters in the string do not need to be next to each other but must appear in sequential order.

例如,序列aabcc包含四个事件再度发生的字符串abc

For example, the sequence "aabcc" contains four occurences of the string "abc"

BC C

B C <强> C

农行 C

AB C <强> C

我想过用常规的前pressions,但只匹配比赛中第一次出现。

I thought about using regular expressions, but that only matches the first occurance of the match.

推荐答案

买者:这是JavaScript的(对不起!)。它也比它需要是可能的方式更加复杂,但是我的强迫症不会是孤独地离开。

Caveat: this is JavaScript (I'm sorry!). It's also probably way more complicated than it needed to be, but my OCD wouldn't leave it alone.

function search(needle, haystack) {
    var needles = needle.split('');
    var haystacks = haystack.split('');
    var matches = [];
    var nI = 0;
    var hI = 0;
    for (hI = 0; hI < haystacks.length; hI++) {
        for (nI = 0; nI < needles.length; nI++) {
            if (haystacks[hI] === needles[nI]) {
                matches.push(nI);
            } else {
                continue;
            }
        }
    }
    matches = matches.reduce(function (acc, el, index) {
        var cur = acc.map[el];
        if (!cur) {
            acc.map[el] = cur = [];
            acc.res.push(cur);
        }
        cur.push(index);
        return acc;
    }, {
        res: [],
        map: {}
    }).res;
    return matches;
}

function allPossibleCases(arr) {
    return combinations(arr).map(function (combination) {
        return combination.join(" ");
    });
}

function combinations(array) {
    if (!array.length) {
        return [];
    }

    array = array.map(function (item) {
        return item instanceof Array ? item : [item];
    });

    function combine(list) {
        var prefixes, combinations;

        if (list.length === 1) {
            return list[0];
        }
        prefixes = list[0];
        combinations = combine(list.slice(1));
        return prefixes.reduce(function (memo, prefix) {
            return memo.concat(combinations.map(function (combination) {
                return [prefix].concat(combination);
            }))
        }, []);
    }

    return combine(array);
}

var r = allPossibleCases(search("abc", "aabcc"));

// r.length = 4, r = array of matches

下面是一个小提琴一起玩。

注:杠杆约code从这个答案它计算其余对象。

Note: leveraged some code from this answer which counts the remaining objects.

这篇关于发现在一组字符使用catch出现特定字符串的数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆