java - Given a string find the longest substring with words that have 2 or more letter in common optimally -


the text of problem says so: find longest substring in given string formed words have 2 or more letters in common(the words must neighbours in substring(one after other)) . restraint: running time must lower o(n^2);

another restriction programme must have method compares 2 words , says if have 2 or more letters in common. function must run in o(n) time.

the way thought of achieving o(n) time in method using hashtables(as see name of method tries achieve "find"). implementation of problem:

public class subiectul1 {     string str1;      subiectul1(string str1){         this.str1 = str1;     }      public boolean find(string str1, string str2){         hashtable<string,integer> hash = new hashtable<string,integer>();         int count = 0;          str1 = str1.tolowercase();         str2 = str2.tolowercase();          for(int = 0; < str1.length(); i++){             hash.put(string.valueof(str1.charat(i)), 1);         }          for(int = 0; < str2.length(); i++){             if(hash.containskey(string.valueof(str2.charat(i)))) {                 count++;                  hash.remove(string.valueof(str2.charat(i)));             }         }          if(count >= 2) return true;          return false;     }      public void solve(){         string[] a_str1 = str1.split(" ");         int n = a_str1.length;         int[] lmax = new int[n];         int[] succ = new int[n];         int max = 0;         int pmax = -1;          lmax[n - 1] = 1;         succ[n - 1] = -1;          for(int = n - 2; >= 0; i--){             max = 0;             pmax = -1;             for(int j = + 1; j < n; j++)                 if(find(a_str1[i],a_str1[j]) && (max < lmax[j])){                     max = lmax[j];                     pmax = j;                 }              lmax[i] = max + 1;             succ[i] = pmax;         }          pmax = 0;         max = lmax[0];          for(int = 1; < n; i++)             if(lmax[i] > max ) {                 pmax = i;                 max = lmax[pmax];             }          int = pmax;         while(i != -1){             system.out.print(a_str1[i] + " ");             = succ[i];         }      } } 

i know if else has better ideas best think of.


Comments