0

Let's just say I have two strings, a & b.

var a = '[email protected]';
var b = 'yahoo12345556';

What I am expecting is result would be yahoo but using a.indexOf(b) would give me -1.

If I change b to yahoo & do a.indexOf(b), it obviously wouldn't give me -1.

Should I match characters in a loop instead? But the two strings aren't of equal length. It's also important that the characters should be in sequence, I am not looking for occurrence of characters.

10
  • so find a substring that's common between the two variables? Commented Aug 4, 2016 at 17:19
  • What is your criteria for match? Longest matching substring between both? Commented Aug 4, 2016 at 17:19
  • Exactly, irrespective of the position of the searched string in the original string. Commented Aug 4, 2016 at 17:20
  • the problem with your problem is that the potential intersection is large... the o on yahoo is also part of john, just like the h in yahoo is part of smith, etc. Commented Aug 4, 2016 at 17:20
  • 1
    en.wikipedia.org/wiki/Longest_common_substring_problem Commented Aug 4, 2016 at 17:22

2 Answers 2

1

It seems your are looking for Longest Common Substring problem. Here is a good javascript implementation with explanations.

Sign up to request clarification or add additional context in comments.

Comments

0

You might be able to use recursion to solve this problem:

function findLongestCommon (a, b, len) {
    for (var i = 0; i < a.length-1; i=i+len) {
        var sub = a.substring(i, len)
        if (len == 0){
            return "";
        }
        else if (sub.indexOf(b) != -1) {
            return a;
        }
        else{
            return findLongestCommon(a, b, len-1);
        }
}

By calling findLongestCommon(a, b, a.length) you will be able to go through every combination of letter starting with the largest (the whole string) to the smallest (one letter) and if no letter is found it will return empty string.

2 Comments

In the question title: "without using indexOf".
@hatchet I dont think the user meant "without using indexOf" but rather "I tried indexOf and it didn't work, any better ideas?". The easiest and quickest way to accomplish the goal is through the use of recursion and indexOf. If you have a better answer then post it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.