Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find whether each character in 1 string is exist in another string, faster than O(n^2)

Given that 2 strings:

String stringA = "WHATSUP";
String stringB = "HATS";

I want to find out whether each character in stringB H A T S exists in stringA

In a junior approach, the process can be done within a nested for-loop which its computation complexity is O(n^2).

for(int i = 0; i < stringA.length(); i++){
    for(int j = 0; j < stringB.length(); j++){
        if(stringA.charAt(i) == stringB.charAt(j))
            //do something
    }
}

I am looking for a faster solution to solve this problem.

like image 252
Kone Man Avatar asked Aug 05 '16 17:08

Kone Man


People also ask

How do you check if a string is present in another string?

Run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index. This can be done by running a nested loop traversing the given string and in that loop running another loop checking for sub-strings starting from every index.

How do you check if a string is a substring of another in C?

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.

How do you check if a string is in another string Python?

Summary. The easiest and most effective way to see if a string contains a substring is by using if ... in statements, which return True if the substring is detected. Alternatively, by using the find() function, it's possible to get the index that a substring starts at, or -1 if Python can't find the substring.

How do you check if a string is present in another string Java?

Java String contains() Method Returns true if the characters exist and false if not.


1 Answers

There is a linear time algorithm.

  1. Convert your stringA to a hash-set of characters that has O(1) membership testing.
  2. Iterate over each character in stringB.
  3. If one of the characters isn't in your hash-set, the test fails.
  4. If there is no failure, the test succeeds.
like image 101
recursive Avatar answered Sep 18 '22 01:09

recursive