Home > Enterprise >  Finding maximum length difference between strings of two arrays
Finding maximum length difference between strings of two arrays

Time:04-07

So I've tried to used a nested loop and add the lengths to a int array and then go through the int array and find the highest number but it doesn't pass the test case and I'm starting to think that maybe I'm overcomplicating this problem and that there's a much simpler approach. Here is what I've tried.

public static int mxdiflg(String[] a1, String[] a2) {
    int maxDiff=0;
    int[] lengths=new int[a1.length*a2.length];
    for(int i=0;i<a1.length;i  ){
      for(int j=0;j<a2.length;j  ){
        lengths[j]=Math.abs(a1[j].length()-a2[i].length());
      }
    }
    for(int i=0;i<lengths.length;i  ){
      if(lengths[i]>maxDiff){
        maxDiff=lengths[i];
      }
        
    }
  
  return maxDiff;
  
}

CodePudding user response:

You can do it like so with two independent loops.

String[] a1 = { "ab", "cdefghik", "lsls" };
String[] a2 = { "a", "cdefghik", "lsls", "abcdefghijkl" };

int max = mxdiflg(a1, a2);
System.out.println(max);

prints

11
  • initialize the minvals to largest int value and the maxvals to 0.
  • each loop finds the min and max of the strings using Math.min and Math.max.
  • once done, find the maximum of the two max values and the minimum of the two min values.
  • the subtract the minimum from the maximum and you have the result.
public static int mxdiflg(String[] a1, String[] a2) {
    int maxa1 = 0, mina1 = Integer.MAX_VALUE, maxa2 = 0,
            mina2 = Integer.MAX_VALUE;
    
    // find max and
    for (String s : a1) {
        int len = s.length();
        maxa1 = Math.max(maxa1, len);
        mina1 = Math.min(mina1, len);
    }
    for (String s : a2) {
        int len = s.length();
        maxa2 = Math.max(maxa2, len);
        mina2 = Math.min(mina2, len);
    }
    
    return Math.max(maxa1, maxa2) - Math.min(mina1, mina2);
}

Note: Due to the peculiarities of various character encodings, String.length does accurately count the characters. As stated in the documentation.

Returns the length of this string. The length is equal to the number of Unicode code units in the string.

As some characters use encoding schemes of more than 8 bits, their reported length would greater than 1.

If this is important, the s.length could be replaced with (int)s.codePoints().count() to handle these encodings.

CodePudding user response:

Assuming Java 8 and a reasonable number of strings in each array, I'd suggest using the following to avoid the nested loop:

int a1max = Arrays.stream(a1).mapToInt(String::length).max().orElse(0);
int a1min = Arrays.stream(a1).mapToInt(String::length).min().orElse(0);
int a2max = Arrays.stream(a2).mapToInt(String::length).max().orElse(0);
int a2min = Arrays.stream(a2).mapToInt(String::length).min().orElse(0);

int maxDiff = Math.max(Math.abs(a2max-a1min), Math.abs(a1max-a2min));
  • Related