Sunday, November 29, 2020

How to check two strings have a common substring in Java?

Given two strings, determine if they share a common substring. A substring may be as small as one character.

For example, the words "j", "and", "jug" share the common substring 'j' The words "or" and "fit" do not share a substring.

Input Format

The first line contains a single integer , the number of test cases.

The following  pairs of lines are as follows:

  • The first line contains string s1
  • The second line contains string s2

Output Format

For each pair of strings, return YES or NO.

Sample Input

2

she

saw

dress

pat

Sample Output

YES

NO

There is a basic approach for this challenge which by using a nested for loop we can detect common substrings (outer for loop traverse through s1 and the inner for loop traverse through s2. For each character in s1, each character of s2 will be matched and if same character is found , return YES and break) , however this solution is not efficient because its complexity is O(n^2).

Below approach is more efficient in which I store each character of the s1 string in a Set and then traverse through s2 String to find whether the above set contains any of the character of s2. 

Find my solution below.

static String twoStrings(String s1, String s2) {
String result="NO";
Set<Character> set1 = new HashSet<Character>();

for (char s : s1.toCharArray()){
set1.add(s);
}

for(int i=0;i<s2.length();i++){
if(set1.contains(s2.charAt(i))){
result = "YES";
break;
}
}
return result;
}




No comments:

Post a Comment