Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

algorithm - Implement a function in JavaScript to determine if a word can be formed from another word by removing repeated letters

I am trying to implement a function in JavaScript called canBeFormed that does this:

const string1 = 'hellooooolooo'
const string2 = 'hellolo'
canBeFormed(string1, string2) // true since by deleting the repeated chars 'o' and 'l' we can form the word 'hellolo'

So if string2 can be formed by string1 if string1 remove some duplicate chars then we return true

I cannot seem to come up with a workable solution to this problem. Can someone give this a shot?

Btw, someone mentioned that this could be solved by dfs + backtracking. Can someone give that approach a try?

To clarify, this function return true if it can form a word from the second string provided by removing one or more repeated letters.

So canBeFormed("heellolo", "hellooooolooo") will return false. canBeFormed("abc", "ac") will return false


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My understanding is that the function should return true if, and only when, the first string can be formed from the second by repeating (consecutively) some characters already present in the first.

The algorithm can be greedy and no backtracking is needed.

function canBeFormed(a, b) {
    let i = 0;
    for (let ch of b) {
        if (ch !== a[i]) {
            // Skip duplicate letters in a
            while (a[i] === a[i-1]) {
                if (++i >= a.length) return false;
            }
            if (ch !== a[i]) return false;
        }
        ++i;
    }
    // Remaining characters should be duplicates
    while (a[i] === a[i-1]) {
        if (++i >= a.length) return true;
    }
    return false;
}

console.log(canBeFormed("hellooooollooo","hellolo")); // true
console.log(canBeFormed("abbcc", "abc")); // true
console.log(canBeFormed("aaabbb", "aaabb")); // true
console.log(canBeFormed("helloooolloo","heellolo")); // false
console.log(canBeFormed("abc", "ac")); // false
console.log(canBeFormed("abbc", "ac")); // false
console.log(canBeFormed("ababc", "abc")); // false
console.log(canBeFormed("abbcca", "abc")); // false
console.log(canBeFormed("aab", "aaab")); // false

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...