longestCommonPrefix function

String longestCommonPrefix(
  1. List<String> strs
)

Finds the longest common prefix string amongst an array of strings.

Returns an empty string if the input list is empty or if there is no common prefix.

Example:

List<String> strs = ["flower", "flow", "flight"];
print(longestCommonPrefix(strs)); // "fl"

Implementation

String longestCommonPrefix(List<String> strs) {
  if (strs.isEmpty) return "";

  String prefix = strs[0];

  for (int i = 1; i < strs.length; i++) {
    prefix = _commonPrefix(prefix, strs[i]);
    if (prefix.isEmpty) break;
  }

  return prefix;
}