Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- String ans;
- public String shortestSuperstring(String[] words) {
- ans = "";
- fun(words, 0);
- // System.out.println(String.format(" %s ", merge2Strings("","baa")));
- // System.out.println(String.format(" %s ", merge2Strings("vv","")));
- return ans;
- }
- public void fun(String[] words, int idx){
- if(idx >= words.length){
- // for(String item : words){
- // System.out.print(String.format(" %s", item));
- // }System.out.println();
- String possibleSolution = mergeOrderedList(words);
- // System.out.println(possibleSolution);
- if(ans == "" || ans.length() > possibleSolution.length()){
- ans = possibleSolution;
- }
- return;
- }
- for(int i=idx;i<words.length;++i){
- swap(words, idx, i);
- fun( words, idx+1);
- swap(words, idx, i);
- }
- }
- public void swap(String[] words, int a, int b ){
- String t = words[a];
- words[a] = words[b];
- words[b] = t;
- }
- public String mergeOrderedList(String[] words){
- if(words.length == 0) return "";
- if(words.length < 2) return words[0];
- String mergedString = words[0];
- for(int i=1;i<words.length;++i){
- mergedString = merge2Strings(mergedString, words[i]);
- }
- return mergedString;
- }
- public String merge2Strings(String a, String b){
- int lena = a.length();
- int lenb = b.length();
- int minLen = Math.min(lena, lenb);
- for(int k=minLen;k>=0;k--){
- boolean flag = true;
- for(int i=lena-k,j=0;i<lena;i++,j++){
- if(a.charAt(i) != b.charAt(j)){
- flag = false; break;
- }
- }
- if(flag == true){
- return a.substring(0,lena-k)+b;
- }
- }
- return a+b;
- }
- }
- /*
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement