JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

PHP finds the common prefix of multiple strings [Case]

Author:JIYIK Last Updated:2025/03/19 Views:

This article shares with you the application of a small algorithm - finding the common prefix of a string array:

array(
   'abcdefg',
   'abcdfio',
   'abcdqle'
)

In the above array string, the common prefix is ​​'abcd'.

The first thing that comes to mind is to start from the first character of the first string and compare it with the characters of other strings in turn. If they are all equal, we save them until one is not equal, then we end the subsequent comparison.

The code is as follows

function commonPrefix($arr){
    $count = strlen($arr[0]);
    $prefix = '';
    for($i=0;$i<$count;$i++){
        $char = $arr[0][$i];
        $flag = true;
        foreach($arr as $val){
            if($char != $val[$i]){
                $flag = false;
                break;
            }
        }
        if(!$flag) break;
        $prefix .= $char;
    }
    return $prefix;
}

This code works great for finding the common prefix of the above array of strings.

But there is a serious bug in the above program. When the length of some strings in the array is smaller than the length of the first string, an error may occur. Let's look at the following array:

array(
  'abcde',
  'abc',
  'abcrhgh',
  'abcdfg',
  'abcfg'
);

We can see from the array above that the common prefix is ​​abc. During the comparison process, when comparing the fourth character d, we check whether the second string has only three characters. Therefore, $arr[1][3] does not have this variable. Therefore, an error is reported.

There are two solutions to this situation

Method 1: Before each comparison, determine whether the variable exists. If it does not exist, terminate the subsequent comparison directly.

Some of the code is as follows:

foreach($arr as $val){
   if(!isset($val[$i]){
            $flag = false;
            break;
   }
   if($char != $val[$i]){
       $flag = false;
       break;
   }
}

Method 2: Before searching and comparing, find out the length of the shortest string in the array and use this length as the termination condition of the loop.

The code is as follows:

function commonPrefix($arr){
         $count = strlen($arr[0]);
for($i = 0;$i<count($arr);$i++){
    if(strlen($arr[$i]) <= $count){
        $count = strlen($arr[$i]);
    }
}
    $prefix = '';
    for($i=0;$i<$count;$i++){
        $char = $arr[0][$i];
        $flag = true;
        foreach($arr as $val){
            if($char != $val[$i]){
                $flag = false;
                break;
            }
        }
        if(!$flag) break;
        $prefix .= $char;
    }
    return $prefix;
}

The above is the code for finding common prefixes in a string array. I hope it will be helpful to you.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

The road to learning sorting algorithms - heap sort

Publish Date:2025/03/19 Views:145 Category:ALGORITHM

Like other sorting algorithms, let's first look at the definition of heap sort. Heapsort : refers to a sorting algorithm designed using the heap data structure. A heap is a structure that approximates a complete binary tree and satisfies th

Distributed thinking in Memcached

Publish Date:2025/03/19 Views:146 Category:ALGORITHM

Memcached is known as a high-performance distributed cache system. Speaking of distribution, Memcached is worth analyzing. Its distribution mechanism is different from that of general distributed service systems. In distributed service syst

My understanding of the Paxos algorithm

Publish Date:2025/03/19 Views:147 Category:ALGORITHM

In a distributed system, a core issue is data consistency. Therefore, the consistency algorithm is of utmost importance in a distributed system. The Paxos algorithm is designed to solve the consistency problem, but it has always been consid

Linked List Merge Sort

Publish Date:2025/03/18 Views:138 Category:ALGORITHM

In this article, we will learn how to sort a linked list using merge sort algorithm. It is one of the most preferred algorithms to sort a linked list because slow pointer random access makes the performance of other algorithms worse (for ex

Deep understanding of Nginx's server block selection algorithm

Publish Date:2025/03/17 Views:95 Category:NETWORK

Nginx is one of the most popular web servers in the world. It can successfully handle high loads with many concurrent client connections and can be used as a web server, mail server, or reverse proxy server. In this article, we will discuss

In-depth understanding of Nginx Location block matching algorithm

Publish Date:2025/03/17 Views:62 Category:NETWORK

Similar to the process that Nginx uses to select the Server block that will handle a request  , Nginx also has an established algorithm to decide which Location block within a Server block to use to handle a request. location block syntax

C# 中的多案例切换语句

Publish Date:2024/01/18 Views:104 Category:编程语言

有两种可用于在 C# 中创建多大小写 switch 语句的语法,即常规 switch 语句和基于范围的 switch 语句。

在 Java 中实现 Dijkstra 算法

Publish Date:2023/11/28 Views:148 Category:Java

本教程描述并演示了 Java 中的 Dijkstra 算法。当找到两个图节点之间的最短路径时,我们可以实现 Dijkstra 算法,这是一种广泛使用的算法。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial