Thursday, September 24, 2020

To String contains compare O(n)

 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.

Solutions:

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 { 
    static String twoStrings(String s1, String s2) {
      Set<Character> a1 = new HashSet<>();
        Set<Character> a2 = new HashSet<>();
        for (int i = 0; i < s1.length(); i++) {
            a1.add(s1.charAt(i));
        }
        for (int i = 0; i < s2.length(); i++) {
            a2.add(s2.charAt(i));
        }
        for (char ch : a1) {
            if (a2.contains(ch)) {
                return "YES";
            } 
        }
        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();
    }
}

No comments:

Post a Comment

Adbox