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 “”.
翻譯蒟蒻
在給定的陣列中找出最常出現的前綴字,如果沒有的話,就回傳空字串 ""。
Example 1:
1
2Input: strs = ["flower","flow","flight"]
Output: "fl"Example 2:
1
2
3Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Solution - JavaScript
Solution 1:
1 | /** |
Solution 2:
1 | /** |
Solution - Ruby
1 | def longest_common_prefix(strs) |
Solution - PHP
1 | function longestCommonPrefix($strs) { |
PHP 方法筆記
empty是一個用來檢查變數是否為空或未設定的函數。
具體而言,empty函數會檢查一個變數是否為以下情況之一:- 變數未被設定(未被賦值)。
- 變數的值為空字串
""。 - 變數的值為
0(作為整數)。 - 變數的值為
"0"(作為字串)。 - 變數的值為
null。 - 變數的值為
false。 - 變數的值為空陣列
array()。 - 變數不存在。
如果變數符合上述任何一種情況,
empty函數將返回true,否則返回false。
sort用來對陣列(array)進行排序的方法。sort會直接修改原始陣列,並返回排序後的結果。如果是要保留原始陣列的副本而對副本進行排序,可以使用array_copy函數。
end用於獲取陣列中最後一個元素的函數。函數的基本語法如下:
1
$lastString = end($strs);
substr是 PHP 中用來取得字串的一個函數,其目的是截取字串的一部分。函數的基本語法如下:
1
2
3
4
5substr(string $string, int $start, int $length = ?) : string
// `$string`: 要截取的原始字串。
// `$start`: 開始截取的位置,以字元索引表示。
// `$length`(可選): 要截取的長度。如果未指定,則截取自 `$start` 至字串結尾的所有字元。在剛剛的解法中:
1
return substr($firstString, 0, $i);
substr($firstString, 0, $i)
用於取得$firstString字串的前0到$i-1的部分,
這就是找到的最長共同前綴(longest common prefix)。例如,如果
$firstString是 “apple” 而$i是 3,
則substr($firstString, 0, 3)將返回 “app”。