Advertisement
YChalk

String Mix

Feb 16th, 2022
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Mixing {
  4.    
  5.     public static String mix(String s1, String s2) {
  6.       // your code
  7.       /*String s1A = s1.replaceAll("[^a-z]", "");
  8.       String s2A = s2.replaceAll("[^a-z]", "");*/
  9.       int[][] count = new int[2][26];
  10.       ArrayList<String> list = new ArrayList<>();
  11.      
  12.       int index = 0;
  13.       for (char c = 'a'; c <= 'z'; c++){
  14.         final char C = c;
  15.         count[0][index] = (int) s1.chars().filter(i -> i == C).count();
  16.         count[1][index] = (int) s2.chars().filter(i -> i == C).count();
  17.         index++;
  18.       }
  19.      
  20.       for (int i = 0; i < 26; i++){
  21.         if (count[0][i] > 1 || count[1][i] > 1){
  22.           int j = i+97;
  23.           char c = (char)j;
  24.           String s = count[0][i] > count[1][i] ? ("1:"+String.join("", Collections.nCopies(count[0][i], String.valueOf(c)))) :
  25.                     count[1][i] > count[0][i] ? ("2:"+String.join("", Collections.nCopies(count[1][i], String.valueOf(c)))) :
  26.                     ("=:"+String.join("", Collections.nCopies(count[1][i], String.valueOf(c))));
  27.           list.add(s);
  28.         }
  29.       }
  30.      
  31.       //Arrays.sort(rank, Comparator.comparingInt(String::length));
  32.       Collections.sort(list, new LengthFirstComparator());
  33.      
  34.       StringBuffer sb = new StringBuffer("");
  35.       for (String s : list){
  36.         if (!s.equals("")){
  37.           sb.append(s);
  38.           sb.append("/");
  39.         }
  40.       }
  41.       if (sb.length()>0){
  42.         sb.deleteCharAt(sb.length()-1);
  43.       }
  44.       return sb.toString();
  45.      
  46.     }
  47.   static class LengthFirstComparator implements Comparator<String> {
  48.     @Override
  49.     public int compare(String o1, String o2) {            
  50.         if (o1.length()!=o2.length()) {
  51.             return o2.length()-o1.length(); //overflow impossible since lengths are non-negative
  52.         }
  53.         return o1.compareTo(o2);
  54.     }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement