I know from reading other questions on the forumn that Array indexing is causing the problem, but I don't know any way around it. I commented where the throw happens. The whole throw is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 35
at assignment4.AnagramUtil.getLargestAnagramGroup(AnagramUtil.java:82)
at assignment4.AnagramTester.main(AnagramTester.java:36)
If anyone has any ideas how I can make this work, let me know. Also, I don't think any more of my methods are relevant in solving this but I can put them here if needed.
/*areAnagrams
* parameters: sorted strings x & y
* returns boolean
* implements sort method
*/
public static boolean areAnagrams(String x, String y)
{
if(sort(x).equals(sort(y)))
return true;
return false;
}
/*
* This function takes a string array and finds the largest anagram group.
* AnagramComparator.insertionSort() sorts the array by placing anagrams together,
* so no sorting is needed.
* I use ArrayList because I want to be able to freely add to the string array.
* returns a new String[]
*/
public static String[] getLargestAnagramGroup(String[] input)
{
String[] s=input;
AnagramComparator.insertionSort(s, new AnagramComparator());
int largestCount = 0, tempCount=1;
ArrayList<String> largest= new ArrayList<String>();
ArrayList<String> temp= new ArrayList<String>();
for(int i=0; i<s.length; i++)
{
//since it's already sorted, we need only to compare.
//add
temp.add(s[i]);
//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 35
if (areAnagrams(s[i],s[i+1])) //at assignment4.AnagramUtil.getLargestAnagramGroup(AnagramUtil.java:82)
{
//add s[i+1] to array list
temp.add(s[i+1]);
tempCount++;
}
else
{
//if tempcount> largestcount, empty contents of largest and make temp largest
if (tempCount>largestCount)
{
if(!largest.isEmpty())
largest.clear();
largest=temp;
largestCount=tempCount;
}
//reset tempcount
tempCount=1;
}
}
String[] result= new String[largest.size()];
for (int j=0;j<largest.size();j++)
result[j]=largest.get(j);
return result;
}
your problem is here:
areAnagrams(s[i],s[i+1])
this will fail when i = s.length - 1 because of i + 1 (when i = s.length it is out of bounds, as length returns the number of elements, yet array index starts at 0)
change
for(int i=0; i<s.length; i++)
to
for(int i=0; i<s.length - 1; i++)
Try changing this line:
for(int i=0; i<s.length; i++)
to this:
for(int i=0; i<s.length-1; i++)
You have a loop
for(int i=0; i<s.length; i++) {...
which means that for the maximum allowable value of i, s[i] will be the last element in s.
But within the loop you are referencing s[i + 1], which is past the end of s.
Related
So as part of a task, I was asked to create an array with randomized values within a range, and then to sort it from smallest to biggest (I used a bubble sort), and then to firstly, print the sum of all the elements in the array, then to list them from smallest to biggest.
My issue is that I keep getting the ArrayIndexOutOfBoundsException error, but cannot find where this problem lies.
You can see in the code that I've put in the randomArrays method, a for loop that creates the random values for the array size I declared in the main method, then, underneath the for loop, I've created an if statement that checks to see if an element's value is bigger than the element after it, if it is, it swaps the place of the elements, until they're all sorted into smallest to biggest, and the loop is terminated.
Any help is much appreciated, thank you :)
public class MyArray {
public static void main(String[] args) {
int[] elements = new int[50];
int min = 0;
int max = 50;
randomArrays(elements, max, min);
}
public static void randomArrays(int[] elements, int max, int min) {
int range = max - min; //defines the range of the integers
int temp;
boolean fixed = false;
while (fixed == false) {
fixed = true;
for (int i = 0; i < elements.length; i++) {
elements[i] = min + (int) (Math.random() * range);
while (i < elements.length) {
if (elements[i] > elements[i + 1]) {
//if 8 > 5
temp = elements[i + 1];
//store 5 in temp
elements[i + 1] = elements[i];
//put the 8 in the 5's place
elements[i] = temp;
fixed = false;
}
i++;
}
}
}
}
//System.out.println(elements[i]);
}
My issue is that I keep getting the ArrayIndexOutOfBoundsException
error, but cannot find where this problem lies.
Problem lies in the condition of the for loop. You get ArrayOutOfBounds exception when i=49 and then you try to access i+1 index which doesn't exists.
Change
for (int i = 0; i < elements.length; i++)
to
for (int i = 0; i < elements.length-1; i++)
As you can already see that your code is going out of the arrays limit.
if you look at your code, following is where this is happening
while (i < elements.length) {
Its this while loop part, so if you change it to correctly loop thru the right number of elements, your problem will be resolved..change your while loop code with this one
while (i < elements.length-1) {
What exactly am I doing wrong here and how do I fix it (please answer like I'm 5 as I am new to java and StackOverflow). The xyzToFront method is the one that should be responsible for the issue. I know there is a code that helps with rearranging/makes it simpler, but I am trying to work with/create my own algorithm according to what I learned.
Here is what I am getting:
+[cat, dog, horse, zebra, zebra]
Expected: [cat, dog, horse, zebra, zebra]
+2
Expected: 2
+3
Expected: 3
-[xantus, xantus, yak, ape, dog, cat]
Expected: [xantus, zebra, yak, ape, dog, cat
Here is the code:
// Complete the methods below. These methods manipulate Arrays of
Strings
// Need help starting this question? In the lesson titled //
"Starting points: Problem Set Questions", go to the // problem titled
"Problem Set 7 - Question 1" for some tips on // how to begin.
import java.util.Arrays;
public class ArrayMethods {
String[] list; //instance variable
/**
* Constructor for objects of class ArrayMethods
*/
public ArrayMethods(String[] list)
{
// initialise instance variables
this.list = list;
}
/**
* Determines if the array is sorted (do not sort)
* When Strings are sorted, they are in alphabetical order
* Use the compareTo method to determine which string comes first
* You can look at the String compareTo method in the Java API
* #return true if the array is sorted, else false.
*/
public boolean isSorted()
{
boolean sorted = true;
// TODO: Write the code to loop through the array and determine that each
// successive element is larger than the one before it
for (int i = 1; i< list.length; i++){
if((list[i].compareTo(list[i-1]))>0){
sorted = false;
}
}
return sorted;
}
/**
* Replaces all but the first and last with the larger of its to neighbors
* You can use the compareTo to determine which string is larger (later in alphabetical
* order).
*/
public void replaceWithLargerNeighbor()
{
for(int i = 1; i<list.length-1; i++){
if ((list[i-1].compareTo(list[i+1]))> 0){
list[i] = list[i-1];
}
else if(list[i-1].compareTo(list[i+1]) < 0){
list[i] = list[i+1];
}
}
}
/**
* Gets the number of duplicates in the array.
* (Be careful to only count each duplicate once. Start at index 0. Does it match any of the other element?
* Get the next word. It is at index i. Does it match any of the words with index > i?)
* #return the number of duplicate words in the array.
*/
public int countDuplicates()
{
int duplicates = 0;
for(int i = 0; i <list.length-1; i++){
for(int j = i+1; j < list.length; j++){
if(list[i].equals(list[j])){
duplicates++;
}
}
}
return duplicates;
}
/**
* Moves any word that starts with x, y, or z to the front of the array, but
* otherwise preserves the order
*/
public void xyzToFront()
{
String index = "";
int insertAt = 0;
for(int i = 0; i<list.length; i++){
boolean startsWith = (list[i].startsWith("x") || list[i].startsWith("y") || list[i].startsWith("z"));
if(startsWith){
index = list[i];
for(int j = i; j>0; j--){
list[j] = list[j-1];
}
list[insertAt] = index;
insertAt++;
}
}
}
/**
* gets the string representation of this array
* #return a string representation of the array. (do this with Arrays.toString(list))
*/
public String toString()
{
return Arrays.toString(list);
} }
The following is the tester method that does not work with my answer for xyzToFront:
String[] animals4 = {"ape", "dog", "xantus", "zebra", "cat", "yak"};
zoo = new ArrayMethods(animals4); zoo.xyzToFront();
System.out.println(zoo.toString()); System.out.println("Expected:
[xantus, zebra, yak, ape, dog, cat]");
Looks like it was "insertAt" and not "0" as I put before. I guess somehow it was overwriting eachother.
for(int j = i; j>insertAt; j--){
I'm doing a beginner Java tutorial on Lists, and am presented with the below problem
// 1) Declare am ArrayList of strings
// 2) Call the add method and add 10 random strings
// 3) Iterate through all the elements in the ArrayList
// 4) Remove the first and last element of the ArrayList
// 5) Iterate through all the elements in the ArrayList, again.
Below is my code
import java.util.ArrayList;
import java.util.Random;
public class Ex1_BasicArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i <= 10; i++){
Random rand = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
sb.append(alphabet.charAt(rand.nextInt(alphabet.length())));
String randy = sb.toString();
list.add(randy);
}
for (int i = 0; i < list.size(); i++){
System.out.print(list.get(i));
}
list.remove(0);
list.remove(list.size()-1);
for (int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
}
}
I have managed to generate an output, but it is incorrect :(
For my first System.out.print(list.get(i)); I'm trying to get an output for 10 String values, but I get 12.
Sample output: nhgacqhlejph
And when I run the second System.out.println(list.get(i));, I get an output for 8 String Values, which is correct if I started out with 10 in the list, but I have 12, so it means that 4 values were removed :/
Sample output:
g
a
c
q
h
l
e
j
Does anyone know where I went wrong with my code?
To repeat:
I wish to get 10 String values of one letter each from the first System.out.print(list.get(i));
I also want to get 2 less String values from the original list by running the second System.out.println(list.get(i));
First, the for loop should stop at i=9 not at i=10. Hence the loop should be as follows:
for (int i = 0; i < 10; i++){
Second, when printing the list after removing the first and last elements, you're not printing a new line to distinguish between the two outputs. You can add a println between them so that they are separated:
for (int i = 0; i < list.size(); i++){
System.out.print(list.get(i));
}
System.out.println();
list.remove(0);
list.remove(list.size()-1);
Having said this, your implementation is not very efficient in that it creates a StringBuilder in every iteration of the loop as well as a Random object. You can create only one Random object to use it for every iteration. You also don't need a StringBuilder to begin with. The program can be simplified to the following, for example:
ArrayList<String> list = new ArrayList<String>();
Random rand = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 10; i++){
list.add(String.valueOf(alphabet.charAt(rand.nextInt(alphabet.length()))));
}
First of all: int i = 0; i <= 10; i++ generates 11 chars.
First loop will produce 11 characters (without newline).
Second loop will produce 9 characters (with newlines).
Therefore you see 12 characters (11 from 1st loop + one from the 2nd) in one line and then 8 characters on next lines
for (int i = 0; i <= 10; i++)
Above for lop runs from 0 till 10 both including (so it runs for 11 times) apart from this your code looks fine. change i<=10 to i<10
I had rewritten the program and you could use this for your testing
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Ex1_BasicArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 10; i++){
Random rand = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder();
sb.append(alphabet.charAt(rand.nextInt(alphabet.length())));
String randy = sb.toString();
list.add(randy);
}
printList(list);
// Remove Elements
list.remove(0);
list.remove(list.size()-1);
printList(list);
}
/**
* #param list
*/
private static void printList(List<String> list) {
System.out.println("List size:"+list.size());
System.out.println("List="+list);
for(String listElement: list){
System.out.println(listElement);
}
}
}
Output of the program is
List size:10
List=[k, g, i, a, g, k, s, s, x, t]
k
g
i
a
g
k
s
s
x
t
List size:8
List=[g, i, a, g, k, s, s, x]
g
i
a
g
k
s
s
x
Note
List entries would vary as they are picked randomly, but size would be 10 & 8 before delete & after delete respectively
So the original code is
// An (unsorted) integer list class with a method to add an
// integer to the list and a toString method that returns the contents
// of the list with indices.
//
// ****************************************************************
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size) {
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
list[numElements] = value;
numElements++;
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString() {
String returnString = "";
for (int i = 0; i < numElements; i++) {
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
and
// ***************************************************************
// ListTest.java
//
// A simple test program that creates an IntList, puts some
// ints in it, and prints the list.
//
// ***************************************************************
import java.util.Scanner ;
public class ListTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
IntList myList = new IntList(10);
int count = 0;
int num;
while (count < 10) {
System.out.println("Please enter a number, enter 0 to quit:");
num = scan.nextInt();
if (num != 0) {
myList.add(num);
count++;
} else {
break;
}
}
System.out.println(myList);
}
}
I need to change the add method to sort from lowest to highest. This is what I tried doing.
// An (unsorted) integer list class with a method to add an
// integer to the list and a toString method that returns the contents
// of the list with indices.
//
// ****************************************************************
public class IntList {
private int[] list;
private int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size) {
list = new int[size];
}
//------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//------------------------------------------------------------
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
list[numElements] = value;
numElements++;
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
list[i] = value;
break;
}
}
}
for (in i = 0; i < list.length; i++) {
}
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString() {
String returnString = "";
for (int i = 0; i < numElements; i++) {
returnString += i + ": " + list[i] + "\n";
}
return returnString;
}
}
The outcome is very wrong. Any one able to steer me in the right direction? I can sort of see why what I have doesn't work, but I can't see enough to fix it.
So I realize I was not very descriptive here the first time. With the exception of the add method modifications the code was not my doing. My assignment is to only touch the add method to sort the array to print out smallest to largest. This is a beginners class and we do little to no practice my only tools for this are some basic understandings of loops and arrays.
I tried redoing it again and came up with this:
if(list[numElements-1] > value){
for(int i=0; i<numElements; i++){
if(list[i]>value){
for(int j = numElements; j>i; j-- ){
list[j] = list[j-1];
}
list[i] = value;
break;
}
}
numElements++;
}
else
{
list[numElements] = value;
numElements++;
}
my input was:8,6,5,4,3,7,1,2,9,10
the output was: 1,10,1,9,10,1,1,2,9,10
this thing is kicking my butt. I understand I want to check the input number to the array and move all numbers higher than it up one space and enter it behind those so it is sorted on entry, but doing so is proving difficult for me. I apologize if my code on here is hard to follow formatting is a little odd on here for me and time only allows for me to do my best. I think break is not breaking the for loop with i like i thought it would. Maybe that is the problem.
The biggest bug I see is using list.length in your for loop,
for(int i = 0; i <list.length; i++)
you have numElements. Also, I think it's i that needs to stop one before like,
for(int i = 0; i < numElements - 1; i++)
and then
for (int j = numElements; j > i; j--)
There are two lines that have to be moved out of the inner loop:
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
// list[i] = value;
// break;
}
list[i] = value;
break:
}
}
In particular, the inner break means that the loop that is supposed to move all larger elements away to make room for the new value only runs once.
You might want to include Java.util.Arrays which has its own sort function:
http://www.tutorialspoint.com/java/util/arrays_sort_int.htm
Then you can do:
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
}
else {
list[numElements] = value;
numElements++;
Arrays.sort(list);
//Or: Java.util.Arrays.sort(list);
}
}
As Eliott remarked, you are getting confused between list.length (the capacity of your list) and numElements (the current size of your list). Also, though, you do not need to completely sort the list on each addition if you simply make sure to insert each new element into the correct position in the first place. You can rely on the rest of the list already to be sorted. Here's a simple and fast way to do that:
public void add(int value) {
if (numElements == list.length) {
System.out.println("Can't add, list is full");
} else {
int insertionPoint = Arrays.binarySearch(list, 0, numElements);
if (insertionPoint < 0) {
insertionPoint = -(insertionPoint + 1);
}
System.arrayCopy(list, insertionPoint, list, insertionPoint + 1,
numElements - insertionPoint);
list[insertionPoint] = value;
numElements += 1;
}
}
That will perform better (though you may not care for this assignment), and it is much easier to see what's going on, at least for me.
Here are some hints.
First, numElements indicates how many elements are currently in the list. It's best if you change it only after you have finished adding your item, like the original method did. Otherwise it may confuse you into thinking you have more elements than you really do at the moment.
There is really no need for a nested loop to do proper adding. The logic you should be following is this:
I know everything already in the list is sorted.
If my number is bigger then the biggest number (which is the one indexed by numElements-1, because the list is sorted) then I can just add my number to the next available cell in the array (indexed by numElements) and then update numElements and I'm done.
If not, I need to start from the last element in the array (careful, don't look at the length of the array. The last element is indexed by numElements-1!), going down, and move each number one cell to the right. When I hit a cell that's lower than my number, I stop.
Moving all the high numbers one cell to the right caused one cell to become "empty". This is where I'm going to put my number. Update numElements, and done.
Suppose you want to add the number 7 to this array:
┌─┬──┬──┬─┬─┐
│3│14│92│-│-│
└─┴──┴──┴─┴─┘
⬆︎ Last element
You move everything starting from the last element (92) to the right. You stop at the 3 because it's not bigger than 7.
┌─┬─┬──┬──┬─┐
│3│-│14│92│-│
└─┴─┴──┴──┴─┘
(The second element will probably still contain 14, but you're going to change that in the next step so it doesn't matter. I just put a - there to indicate it's now free for you to enter your number)
┌─┬─┬──┬──┬─┐
│3│7│14│92│-│
└─┴─┴──┴──┴─┘
⬆︎ Updated last element
This requires just one loop, without nesting. Be careful and remember that the array starts from 0, so you have to make sure not to get an ArrayIndexOutOfBoundsException if your number happens to be lower than the lowest one.
One problem I spotted is that: you are trying to insert the newly added number into the array. However your loop:
for (int i = 0; i < list.length; i++) {
if (list[i] > value) {
for (int j = list.length - 1; j > i; j--) {
list[j] = list[j - 1];
list[i] = value;
break;
}
}
}
is always looped through the total length of the array, which is always 10 in your test, rather than the actual length of the array, i.e. how many numbers are actually in the array.
For example, when you add the first element, it still loops through all 10 elements of the array, although the last 9 slots does not have value and are automatically assigned zero.
This caused your if statement always returns true:
if (list[i] > value)
if you have to write the sort algorithm yourself, use one of the commonly used sorting algorithm, which can be found in Wikipedia.
If any one was curious I finally worked it out. Thank you to everyone who replied. This is what i ended up with.
public void add(int value)
{
if(numElements == 0){
list[numElements] = value;
numElements++;
}
else{
list[numElements] = value;
for(int check = 0; check < numElements; check++){
if(list[check] > value){
for(int swap = numElements; swap> check; swap--){
list[swap] = list[swap-1];
}
list[check] = value;
break;
}
}
numElements++;
}
}
so my original is the same but we have to make another class
A Sorted Integer List
File IntList.java contains code for an integer list class. Save it to your project and study it; notice that the only things you can do are create a list of a fixed size and add an element to a list. If the list is already full, a message will be printed. File ListTest.java contains code for a class that creates an IntList, puts some values in it, and prints it. Save this to your folder and compile and run it to see how it works.
Now write a class SortedIntList that extends IntList. SortedIntList should be just like IntList except that its elements should always be in sorted order from smallest to largest. This means that when an element is inserted into a SortedIntList it should be put into its sorted place, not just at the end of the array. To do this you’ll need to do two things when you add a new element:
Walk down the array until you find the place where the new element should go. Since the list is already sorted you can just keep looking at elements until you find one that is at least as big as the one to be inserted.
Move down every element that will go after the new element, that is, everything from the one you stop on to the end. This creates a slot in which you can put the new element. Be careful about the order in which you move them or you’ll overwrite your data!
Now you can insert the new element in the location you originally stopped on.
All of this will go into your add method, which will override the add method for the IntList class. (Be sure to also check to see if you need to expand the array, just as in the IntList add() method.) What other methods, if any, do you need to override?
To test your class, modify ListTest.java so that after it creates and prints the IntList, it creates and prints a SortedIntList containing the same elements (inserted in the same order). When the list is printed, they should come out in sorted order.
Need java function to find the longest duplicate substring in a string
For instance, if the input is “banana”,output should be "ana" and we have count the number of times it has appeared in this case it is 2.
The solution is as below
public class Test{
public static void main(String[] args){
System.out.println(findLongestSubstring("i like ike"));
System.out.println(findLongestSubstring("madam i'm adam"));
System.out.println(findLongestSubstring("When life hands you lemonade, make lemons"));
System.out.println(findLongestSubstring("banana"));
}
public static String findLongestSubstring(String value) {
String[] strings = new String[value.length()];
String longestSub = "";
//strip off a character, add new string to array
for(int i = 0; i < value.length(); i++){
strings[i] = new String(value.substring(i));
}
//debug/visualization
//before sort
for(int i = 0; i < strings.length; i++){
System.out.println(strings[i]);
}
Arrays.sort(strings);
System.out.println();
//debug/visualization
//after sort
for(int i = 0; i < strings.length; i++){
System.out.println(strings[i]);
}
Vector<String> possibles = new Vector<String>();
String temp = "";
int curLength = 0, longestSoFar = 0;
/*
* now that the array is sorted compare the letters
* of the current index to those above, continue until
* you no longer have a match, check length and add
* it to the vector of possibilities
*/
for(int i = 1; i < strings.length; i++){
for(int j = 0; j < strings[i-1].length(); j++){
if (strings[i-1].charAt(j) != strings[i].charAt(j)){
break;
}
else{
temp += strings[i-1].charAt(j);
curLength++;
}
}
//this could alleviate the need for a vector
//since only the first and subsequent longest
//would be added; vector kept for simplicity
if (curLength >= longestSoFar){
longestSoFar = curLength;
possibles.add(temp);
}
temp = "";
curLength = 0;
}
System.out.println("Longest string length from possibles: " + longestSoFar);
//iterate through the vector to find the longest one
int max = 0;
for(int i = 0; i < possibles.size();i++){
//debug/visualization
System.out.println(possibles.elementAt(i));
if (possibles.elementAt(i).length() > max){
max = possibles.elementAt(i).length();
longestSub = possibles.elementAt(i);
}
}
System.out.println();
//concerned with whitespace up until this point
// "lemon" not " lemon" for example
return longestSub.trim();
}
}
This is a common CS problem with a dynamic programming solution.
Edit (for lijie):
You are technically correct -- this is not the exact same problem. However this does not make the link above irrelevant and the same approach (w.r.t. dynamic programming in particular) can be used if both strings provided are the same -- only one modification needs to be made: don't consider the case along the diagonal. Or, as others have pointed out (e.g. LaGrandMere), use a suffix tree (also found in the above link).
Edit (for Deepak):
A Java implementation of the Longest Common Substring (using dynamic programming) can be found here. Note that you will need to modify it to ignore "the diagonal" (look at the Wikipedia diagram) or the longest common string will be itself!
In Java : Suffix Tree.
Thanks to the ones that have found how to solve it, I didn't know.