Source: Internet
Author: User

Tags: func contains two-dimensional array of dimensions code lookup function array functions

The original topic is this: Write a function to find the longest common prefix in a string array. Returns an empty string "" If there is no public prefixExample 1:

Input: ["Flower", "flow", "flight"]

Output: "FL"

Example 2:

Input: ["dog", "racecar", "car"]

Output: ""

Explanation: The input does not exist with a public prefix.

Description

All inputs contain only lowercase letters A-Z.

`The code is the following class test{public function A6 ($arr) {//Gets the first value in the string array, with the value of this element as the base, and the elements after the array are compared to this $comm On_str= $arr [0]; Iterate through the array, cut each string into groups, cut the Array (0=>array (), 1=>array () ... n=>array ()), and you can think of the resulting result as a matrix, The number of rows in the matrix is how many strings, that is, the subscript of the incoming array, the number of columns is the subscript of the array after each string is cut. foreach ($arr as $key = = $value) {$arr [$key] = Str_split ($value); }//To Here, $arr has become a two-dimensional array $length = count ($arr); $temp = $arr [0]; Because we are going to compare each string to the first one in the incoming array, we take the first one out as a base value $len = count ($temp); The $i in this for loop is the column of the matrix so that the I-bit for ($i =0; $i < $len, $i + +) of each substring array can be taken out, which is the line of the matrix in the For loop, which is the $n into the array of strings for ($n =1; $n < $length; $n + +) {//If the first bit of the base value is not equal to the I bit of the subsequent string, the base string is truncated before the first if ($temp [$i]!= $arr [$n] [$i]) {//Of course there is a special case, that is, compared to the No. 0 bit has not finished, the BI dropped, then return without the same prefix if ($i = = 0) {return ' does not have the same prefix '; } return substr ($common _str,0, $i); }}//Here The judgment is to join the cardinality string traversal complete, all the same, then we return the cardinality string if ($i = = $len-1) { return $commen _str; } } }}`

PHP (5) "Longest common prefix" algorithm problem

Related Article