Two Strings - HackerRank Solution.

NOTE: If you are copying my code then its an advice to you to copy it after downloading it to avoid any kind of compilation error its link is available at the bottom of the source code.


Given two strings, determine if they share a common substring. A substring may be as small as one character.
For example, the words "a", "and", "art" share the common substring . The words "be" and "cat" do not share a substring.
Function Description
Complete the function twoStrings in the editor below. It should return a string, either YES or NO based on whether the strings share a common substring.

twoStrings has the following parameter(s):
  • s1, s2: two strings to analyze .
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 .
  • The second line contains string .
Constraints
  •  and  consist of characters in the range ascii[a-z].
Output Format
For each pair of strings, return YES or NO.
Sample Input
2
hello
world
hi
world
Sample Output
YES
NO
Explanation
We have  pairs to check:
  1. . The substrings  and  are common to both strings.
  2.  and  share no common substrings.

SOURCE CODE




import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

// Complete the twoStrings function below.
static String twoStrings(String s1, String s2) {
char ar[]=s1.toCharArray();
char arr[]=s2.toCharArray();
ArrayList<Character> al=new ArrayList<Character>();
ArrayList<Character> all=new ArrayList<Character>();
for(char ch:ar)
{
al.add(ch);
}
for(char ch:arr)
{
all.add(ch);
}
int flag=0;
for(char i='a';i<='z';i++)
{
if(al.contains(i) && all.contains(i))
{
flag=1;
break;
}
}
if(flag==1)
{
return("YES");
}
else
{
return("NO");
}
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int qItr = 0; qItr < q; qItr++) {
String s1 = scanner.nextLine();

String s2 = scanner.nextLine();

String result = twoStrings(s1, s2);

bufferedWriter.write(result);
bufferedWriter.newLine();
}

bufferedWriter.close();

scanner.close();
}
}


Click here to Download



RESULT




If you have any question then leave a comment below I will do my best to answer that question.

Comments

Popular posts from this blog

[Question 3] ISC 2017 Computer Practical Paper Solved – Caesar Cipher.

Pattern of your own name.

Designing Patterns - Print 'Z'.