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.
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.
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.
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.
Java String contains() Method Returns true if the characters exist and false if not.
There is a linear time algorithm.
stringA
to a hash-set of characters that has O(1) membership testing.stringB
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With