write a static method called bothStart that allows the user to input two Strings and returns the String that is the longest substring s such that both inputs start with s.


For example,


bothStart( "radar dish", "radical food" ) returns "rad"


bothStart( "radar disk", "disk radar" ) returns ""


bothStart( "radar installation", "" ) returns ""


bothStart( "Mendacious", "Mendicant" ) returns "Mend"


bothStart( "FRANKLY", "frank" ) returns ""

Respuesta :

Answer:

  1.    public static String bothStart(String text1, String text2){
  2.        String s = "";
  3.        if(text1.length() > text2.length()) {
  4.            for (int i = 0; i < text2.length(); i++) {
  5.                if (text1.charAt(i) == text2.charAt(i)) {
  6.                    s += text1.charAt(i);
  7.                }else{
  8.                    break;
  9.                }
  10.            }
  11.            return s;
  12.        }else{
  13.            for (int i = 0; i < text1.length(); i++) {
  14.                if (text1.charAt(i) == text2.charAt(i)) {
  15.                    s += text1.charAt(i);
  16.                }else{
  17.                    break;
  18.                }
  19.            }
  20.            return s;
  21.        }
  22.    }

Explanation:

Let's start with creating a static method bothStart() with two String type parameters, text1 & text2 (Line 1).  

Create a String type variable, s, which will hold the value of the longest substring that both inputs start with the same character (Line 2).

There are two possible situation here: either text1 longer than text2 or vice versa. Hence, we need to create if-else statements to handle these two position conditions (Line 4 & Line 13).

If the length of text1 is longer than text2, the for-loop should only traverse both of strings up to the length of the text2 (Line 5). Within the for-loop, we can use charAt() method to extract individual character from the text1 & text2 and compare with each other (Line 15). If they are matched, the character should be joined with the string s (Line 16). If not, break the loop.

The program logic from (Line 14 - 20) is similar to the code segment above (Line 4 -12) except for-loop traverse up to the length of text1 .

At the end, return the s as output (Line 21).