Pergunta de entrevista da empresa Google

Write a function that will return the second longest string in a list of strings. You have to do a single pass on the list.

Respostas da entrevista

Sigiloso

13 de jun. de 2011

public int find2ndLongest(String[] strAry) { int max_1 = 0; int max_2 = -1; if (strAry == null || strAry.length == 0) { System.err.println(" Array is NULL or length is zero!!"); return -99; } if (strAry.length == 1) { System.err.println(" Array length is ONE. No Max 2!!"); return -99; } int i = 0; while (i strAry[max_1].length()) { max_2 = max_1; max_1 = i; } else { if (max_2 < 0 || strAry[max_2].length() < strAry[i].length()) max_2 = i; } i++; } //end while return max_2; }

Sigiloso

27 de jun. de 2011

while I agree with lkcfree's approach, the question asks to return the second longest "string", not the length itself.

Sigiloso

24 de mar. de 2012

come on medicine23 :)

Sigiloso

24 de mar. de 2012

function secondLargest($str) { $max1 = $max2 = ""; $max1Len = $max2Len = 0; $arr = explode($str, " "); foreach ($arr as $entry) { $len = strlen($entry); if ($len > $max1Len) { $max2Len = $max1Len; $max2 = $max1; $max1Len = $len; $max1 = $entry; } else { if ($len > $max2Len) { $max2Len = $len; $max2 = $entry; } } } return $max2; }