Advertisement
veryinnocentboy

Find the Shortest Superstring

May 23rd, 2021
780
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. class Solution {
  2.     String ans;
  3.    
  4.    
  5.     public String shortestSuperstring(String[] words) {
  6.         ans = "";
  7.        
  8.         fun(words, 0);
  9.        
  10.         // System.out.println(String.format(" %s ", merge2Strings("","baa")));
  11.         // System.out.println(String.format(" %s ", merge2Strings("vv","")));
  12.         return ans;
  13.     }
  14.     public void fun(String[] words, int idx){
  15.         if(idx >= words.length){
  16.            
  17.             // for(String item : words){
  18.             //     System.out.print(String.format(" %s", item));
  19.             // }System.out.println();
  20.             String possibleSolution = mergeOrderedList(words);
  21.             // System.out.println(possibleSolution);
  22.             if(ans == "" || ans.length() > possibleSolution.length()){
  23.                 ans = possibleSolution;
  24.             }
  25.             return;
  26.         }
  27.         for(int i=idx;i<words.length;++i){
  28.             swap(words, idx, i);
  29.             fun( words, idx+1);
  30.             swap(words, idx, i);
  31.         }
  32.     }
  33.     public void swap(String[] words, int a, int b ){
  34.         String t = words[a];
  35.         words[a] = words[b];
  36.         words[b] = t;
  37.     }
  38.     public String mergeOrderedList(String[] words){
  39.         if(words.length == 0) return "";
  40.         if(words.length < 2) return words[0];
  41.         String mergedString = words[0];
  42.         for(int i=1;i<words.length;++i){
  43.             mergedString = merge2Strings(mergedString, words[i]);
  44.         }
  45.         return mergedString;
  46.     }
  47.     public String merge2Strings(String a, String b){
  48.        
  49.         int lena = a.length();
  50.         int lenb = b.length();
  51.         int minLen = Math.min(lena, lenb);
  52.         for(int k=minLen;k>=0;k--){
  53.             boolean flag = true;
  54.             for(int i=lena-k,j=0;i<lena;i++,j++){
  55.                 if(a.charAt(i) != b.charAt(j)){
  56.                     flag = false; break;
  57.                 }
  58.             }
  59.             if(flag == true){
  60.                 return a.substring(0,lena-k)+b;
  61.             }
  62.         }
  63.         return a+b;
  64.     }
  65. }
  66.  
  67. /*
  68.  
  69. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement