1078-findOcurrences.js 1.06 KB
/**
 * @param {string} text
 * @param {string} first
 * @param {string} second
 * @return {string[]}
 */
var findOcurrences2 = function(text, first, second) {
    let target = `${first} ${second} `;
    let rs = [];

    while (text) {
        let i = text.indexOf(target);
        if (i >= 0) {
            console.info(text, i);
            text = text.substr(i + target.length);
            console.info('==>', text);
            let m = /^(\w+)\b.*/.exec(text);
            if (m) {
                rs.push(m[1]);
            }
        } else {
            break;
        }
    }
    
    return rs;
};

var findOcurrences = function(text, first, second) {
    let words = text.split(' ');
    let rs = [];

    for (let i = 0; i < words.length - 2; i++) {
        if (words[i] === first && words[i+1] === second && words[i+2]) {
            rs.push(words[i+2]);
            i++;
        }
    }
    
    return rs;
};

console.info(findOcurrences("we will we will rock you", "we", "will"));
console.info(findOcurrences("alice is a good girl she is a good student", "a", "good"));