Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

emre-tarhan/leetcode-longest-common-prefix

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

4 Commits

Repository files navigation

Leetcode Longest Common Prefix

Leetcode.com Longest Common Prefix Solution (PHP)
[Runtime 8ms (faster than 90%), 19MB memory usage (less than 80%) ]
https://leetcode.com/problems/longest-common-prefix/

a

Problem

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:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

Solution

class Solution {
 function longestCommonPrefix($strs) {
 $strs_count = count($strs);
 if ($strs_count < 2) {
 return $strs_count ? $strs[0] : '';
 }
 
 $equal = $strs[0];
 for ($n = 1; $n < $strs_count; $n++) {
 $a = str_split($equal);
 $b = str_split($strs[$n]);
 $equal = '';
 $max = min(count($a), count($b));
 
 for($i = 0; $i < $max; $i++) {
 if ($a[$i] == $b[$i]) {
 $equal .= $b[$i];
 }else {
 break;
 }
 }
 
 if (!$equal) return $equal;
 }
 
 return $equal;
 }
}

About

Leetcode.com Longest Common Prefix Solution [8ms, 19MB memory usage (less than 80%) ]

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

AltStyle によって変換されたページ (->オリジナル) /