JAVA Maximum Length Difference

URL Link //n.sfs.tw/15362

2021-08-24 11:19:49 By

You are given two arrays a1 and a2 of strings.

Each string is composed with letters from a to z.

Let x be any string in the first array and y be any string in the second array.

Find max(abs(length(x) − length(y)))

If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).

example output:

a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13

my solution:

import java.util.*;

class MaxDiffLength {
    
    public static int mxdiflg(String[] a1, String[] a2) {
        // your code
      if (a1 == null || a1.length == 0 || a2 == null || a2.length == 0)
          {return -1;}

        int maxVal = Integer.MIN_VALUE;
        for (int i = 0; i < a1.length; i++)
        {
          for (int j = 0; j < a2.length; j++)
          {
            int diff = Math.abs(a1[i].length() - a2[j].length());
            if (diff > maxVal){
              maxVal = diff;
              }
          }
        }

        return maxVal;
    }

clever solution:

import java.util.Arrays;
class MaxDiffLength {
  public static int mxdiflg(String[] a1, String[] a2) {
    if(a1.length == 0 || a2.length == 0) return -1;
    return Math.max(Arrays.stream(a1).mapToInt(s -> s.length()).max().getAsInt() - Arrays.stream(a2).mapToInt(s -> s.length()).min().getAsInt(),
                    Arrays.stream(a2).mapToInt(s -> s.length()).max().getAsInt() - Arrays.stream(a1).mapToInt(s -> s.length()).min().getAsInt());
  }
}

best practice:

class MaxDiffLength {
    
    public static int mxdiflg(String[] a1, String[] a2) {
        if(a1.length==0||a2.length==0)
            return -1;

        int b1=0, b2=0;
        int l1=Integer.MAX_VALUE, l2=Integer.MAX_VALUE;

        for (String s : a1) {
            b1 = Math.max(b1, s.length());
            l1 = Math.min(l1, s.length());
        }
        for (String s : a2) {
            b2 = Math.max(b2, s.length());
            l2 = Math.min(l2, s.length());
        }

        return Math.max(Math.abs(b2-l1), Math.abs(b1-l2));
    }
}

key point: need to understand String length and length() are different method

reference:

https://medium.com/cubemail88/java-%E4%B8%AD%E7%9A%84-length-length-size-%E4%B8%80%E6%AC%A1%E6%91%B8%E9%80%8F%E9%80%8F-24b82cb41e22