November 17, 2023

Viiisit [LeetCode] - 14. Longest Common Prefix

#php#javascript#ruby

keep learning, keep coding!

Problem - Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string “”.

翻譯蒟蒻

在給定的陣列中找出最常出現的前綴字,如果沒有的話,就回傳空字串 ""


Solution - JavaScript

Solution 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (strs.length === 0) {
return "";
}

for (let i = 0; i < strs[0].length; i++) {
let char = strs[0][i];

// 比較該字母在其他字串相同位置的字母
for (let j = 1; j < strs.length; j++) {
if (i >= strs[j].length || char !== strs[j][i]) {
return strs[0].substring(0, i);
}
}
}

return strs[0];
};

Solution 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* @param {string[]} strs
* @return {string}
*/
var longestCommonPrefix = function(strs) {
if (strs.length === 0) {
return "";
}

// 將陣列排序,這樣具有相同前綴的字串就會被排在一起
strs.sort();

// 比較排序後的陣列的第一個字串和最後一個字串的每個字母
let firstString = strs[0];
let lastString = strs[strs.length - 1];
let i = 0;

// 如果找到不同的字母或某個字串的長度不足,就返回目前的前綴
while (i < firstString.length && firstString[i] === lastString[i]) {
i++;
}

return firstString.substring(0, i);
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def longest_common_prefix(strs)
return "" if strs.empty?

# 先排序,並更新 strs 陣列
strs.sort!

# 比較排序後的陣列的第一個字串和最後一個字串的每個字符
first_string, last_string = strs.first, strs.last
i = 0

while i < first_string.length && first_string[i] == last_string[i]
i += 1
end

first_string[0, i]
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function longestCommonPrefix($strs) {
if (empty($strs)) {
return "";
}

sort($strs);

$firstString = $strs[0];
$lastString = end($strs);
$i = 0;

while ($i < strlen($firstString) && $firstString[$i] == $lastString[$i]) {
$i++;
}

return substr($firstString, 0, $i);
}

$strs1 = ["flower", "flow", "flight"];
$strs2 = ["dog", "racecar", "car"];

echo longestCommonPrefix($strs1); // "fl"
echo longestCommonPrefix($strs2); // ""

PHP 方法筆記




LeetCode 傳送門 - Longest Common Prefix