Kerat
Kerat

Reputation: 13

Find the longest String in an array recursively

public static String rMax(String[] s){
    if (s.length == 1){
         return s[0];
    }else {
        String[] newArray = Arrays.copyOfRange(s, 1, s.length);
        String maxInNewArray = rMax(newArray);
        String currentString = s[0];
        
        if(currentString.length() > maxInNewArray.length()) {
            return currentString;
        }else 
            return maxInNewArray;
    }
}

The above code works but I am looking for an alternative way of coding this one instead of using Arrays.copyOfRange(). Any help is appreciated.

Upvotes: 0

Views: 506

Answers (1)

Stefan Haustein
Stefan Haustein

Reputation: 18793

You could just add a helper adding a start position to consider, avoiding the copy:

public static String rMax(String[] s){
  return rMax(s, 0)
}

public static String rMax(String[] s, int start){
    if (start + 1 == s.length){
         return s[start];
    }else {
        String maxInNewArray = rMax(s, start + 1);
        String currentString = s[start];
        
        if(currentString.length() > maxInNewArray.length()) {
            return currentString;
        }else 
            return maxInNewArray;
    }
}

Upvotes: 1

Related Questions