w3resource
Java Programming Exercies

Java String Exercises: Check whether two strings are interleaving of a specified string

Java String: Exercise-36 with Solution

Write a Java program to check whether two strings are interleaving of a given string. Assuming that the unique characters in both strings.

Pictorial Presentation:

Java String Exercises: Check whether two strings are interleaving of a specified string

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 public static void main(String args[]) {
  String str1 = "MNO";
  String str2 = "PQ";
  String str3 = "PMQNO";
  System.out.println("The given string is: " + str3);
  System.out.println("The interleaving strings are " + str1 + " and " + str2);
  System.out.println("The given string is interleaving: " + checkInterleaved(str1, str2, str3));
 }
 private static boolean checkInterleaved(String str1, String str2, String CheckInString) {
  int i = 0, j = 0, k = 0;
  if (str1.length() + str2.length() != CheckInString.length()) {
   return false;
  }
  while (k < CheckInString.length()) {
   if (i < str1.length() && str1.charAt(i) == CheckInString.charAt(k)) {
    i++;
   } else if (j < str2.length() && str2.charAt(j) == CheckInString.charAt(k)) {
    j++;
   } else {
    return false;
   }
   k++;
  }
  if (!(i == str1.length() && j == str2.length() && k == CheckInString.length())) {
   return false;
  }
  return true;
 }
}

Sample Output:

The given string is: PMQNO
The interleaving strings are MNO and PQ
The given string is interleaving: true

The given string is: PNQMO
The interleaving strings are MNO and PQ
The given string is interleaving: false

N.B.: In the 2nd case, in interleave string, N comes before M and in original string str1 = MNO (N comes after M) So it is not interleaved.

Flowchart:

Flowchart: Java String Exercises - Check whether two strings are interliving of a specified string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to print all permutations of a given string with repetition.
Next: Write a Java program to find Length of the longest substring without repeating characters

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming