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;
}




Finding whether a given string has balanced parenthesis using Java Stack

 Challenge: Given a string in the stdin with a set of parenthesis [{[()]}] and the stdout should print either true or false based on whether the parenthesis are matched or not

e.g: 

{} --> true

{[()]} -->true

{[}] -- > false

Solution : I am going to use a Java Stack to resolve this problem following the below approach.

1.use stdin to read the input

2.iterate reading from stdin while there are more inputs

3.store each string in a variable and validate

4.validation >> 

    a. loop through each character of the string

    b.If current character is ( OR { OR [ then add the value to the Stack

    c.If the current character is ) OR } OR ] then pop a value from the Stack and compare it with the current character

   d. if matches then result is true , continue ; else set result as false 

Below is the coding

-----------------------------------------------------------------------------------------------------------------------------

package com.hackerrank;

import java.util.Scanner;
import java.util.Stack;

public class Main {

/**
* Main method
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); //stdin
while(scanner.hasNext()){ //reading continues till stdin has more inputs
String input = scanner.nextLine(); //read String
System.out.println(checkBalancedLine(input)); //validate and print result
}
}

/**
* This method validates the string with balanced paranthesis
* @param inputLine
* @return true or false
*/
public static boolean checkBalancedLine(String inputLine){
boolean balanced =false;

Stack<String> stringStack = new Stack<String>();

for(int i=0;i<inputLine.length();i++){
if((inputLine.charAt(i)=='(') || (inputLine.charAt(i)=='{') || (inputLine.charAt(i)=='[')) { //if the character is ([{ then add to the stack
stringStack.add(String.valueOf(inputLine.charAt(i)));
}
if((inputLine.charAt(i)==')') || (inputLine.charAt(i)=='}') || (inputLine.charAt(i)==']')) { //if the character is )]} then pop the stack and compare the ith value against the popped value
if(!stringStack.isEmpty()) {
String poppedString = stringStack.pop();
if (inputLine.charAt(i) == ')' && poppedString.equalsIgnoreCase("(")) {
balanced = true;
} else if (inputLine.charAt(i) == ']' && poppedString.equalsIgnoreCase("[")) {
balanced = true;
} else if (inputLine.charAt(i) == '}' && poppedString.equalsIgnoreCase("{")) {
balanced = true;
} else {
balanced = false;
}
}
}
}
return balanced;
}
}

   Console