Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the longest common prefix of two strings

I want to find the longest common prefix of two strings. Is there a way to loop my last couple of if statements so that I can end at the last characters that do not match each other?

System.out.println("Enter the first string: ");
String s = input.nextLine();

System.out.println("Enter the second string: ");
String s2 = input.nextLine();

//check if first characters are same
if (s.charAt(0) != s2.charAt(0)) {
  System.out.println(""+s+ " and "+s2+ " have no common prefix");
  System.exit(0);
    }

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(0));

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(1));

if (s.charAt(0) == s2.charAt(0))
  System.out.print(" "+s.charAt(2));  
  }
}

Example:

Enter first string: Welcome to c++

Enter second string: Welcome to java

The code should return Welcome to as the common prefix.

like image 815
afrojuju_ Avatar asked Mar 18 '14 23:03

afrojuju_


People also ask

What is the longest common prefix?

The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters.

How do you find the longest common prefix in a string python?

To solve this, we will take the first string as curr, now take each string from the array and read them character by character, and check the characters between curr, and the taken string one by one. If they are same go for next character, otherwise break the loop, and update the curr as the substring that has matched.


2 Answers

try this. I guess this is what you are trying to achieve. If this is correct I will add explanation later

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s = "Hello Wo";
        String s2 = "Hello World";
        String small,large;
         if(s.length() > s2.length()) 
            {small = s2;large = s;}
          else
            {small = s;large = s2;}
        int index = 0;    
        for(char c: large.toCharArray())
        {
            if(index==small.length()) break;
            if(c != small.charAt(index)) break;
            index++;
        }
        if(index==0)
          System.out.println(""+s+ " and "+s2+ " have no common prefix");
        else
          System.out.println(large.substring(0,index));
    }
}

Edit:

  1. I find the larger of the strings and choose it to be the outer string to loop throught
  2. toCharArray() converts the string into characters so you can loop through each characters in the string using Java's foreach (For more click[1])
  3. Inside the loop you should exit on two conditions
    • End of the string (I use length to find if I reach end of smaller string)
    • no more matching characters between two strings
  4. you increment the index until you break out in one of the above conditions
  5. By the time you break out of the for loop, index will contain the last index where both string are continuously equal.
  6. If index = 0. just say no matches else print characters from 0 until index
like image 74
Dexters Avatar answered Oct 05 '22 22:10

Dexters


Maybe something like:

int sLength = s.length(),
    s2Length = s2.length(),
    minLength = (sLength < s2Length) ? sLength : s2Length;

for (int i = 0; i < minLength; i++) {
    if (s.charAt(i) == s2.charAt(i)) {
        System.out.println(s.charAt(i));
    }
    else {
        break;
    }
}

But more details about your question would be great.

Edit: It depends what @afrojuju_ wants to do. That's not clear. Some more logic may be added to accomplish the desired behavior.

Edit 2: Added string length comparison as pointed out by @JavaBeast.

like image 31
zrac Avatar answered Oct 05 '22 22:10

zrac