Home > Software engineering >  Given an array of strings, return another array containing all of its longest strings. using Dart
Given an array of strings, return another array containing all of its longest strings. using Dart

Time:11-27

Given an array of strings, return another array containing all of its longest strings.

Example

For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be solution(inputArray) = ["aba", "vcd", "aba"].

[execution time limit] 4 seconds (dart)

[input] array.string inputArray

[input] array.string inputArray

A non-empty array.

Guaranteed constraints: 1 ≤ inputArray.length ≤ 10, 1 ≤ inputArray[i].length ≤ 10.

[output] array.string

[output] array.string

Array of the longest strings, stored in the same order as in the inputArray.

I know that the javascript code answer of the above question but did't know how to write it into dart. this is the javascript //

  var maxLength = Math.max(...inputArray.map(s => s.length));
    return inputArray.filter(s => s.length === maxLength);

CodePudding user response:

You can sort the list by its item's length and then search for items that have equal length to the longest item in sorted list. like this:

var inputArray = ["aba", "aa", "ad", "vcd", "aba"];
inputArray.sort(
  (a, b) => b.length.compareTo(a.length),
);
var result = inputArray
    .where((element) => element.length == inputArray.first.length)
    .toList();
print("inputArray = $result"); //[aba, vcd, aba]

CodePudding user response:

This is pretty easy.

final inputArray = ["aba", "aa", "ad", "vcd", "aba"];
inputArray.map((e) => e.length).toList().sort();
inputArray.retainWhere((el) => el.length == inputArray.first.length);

log(inputArray.toString()); // [aba, vcd, aba]

Output:

[aba, vcd, aba]
  • Related