finding common prefix of array of strings

后端 未结 17 1695
一向
一向 2020-11-29 06:15

I have an array like this:

$sports = array(
\'Softball - Counties\',
\'Softball - Eastern\',
\'Softball - North Harbour\',
\'Softball - South\',
\'Softball -         


        
17条回答
  •  情话喂你
    2020-11-29 06:46

    
        // Common prefix
        $common = '';
    
        $sports = array(
        'Softball T - Counties',
        'Softball T - Eastern',
        'Softball T - North Harbour',
        'Softball T - South',
        'Softball T - Western'
        );
    
        // find mini string
        $minLen = strlen($sports[0]);
        foreach ($sports as $s){
            if($minLen > strlen($s))
                $minLen = strlen($s);
        }
    
    
        // flag to break out of inner loop
        $flag = false;
    
        // The possible common string length does not exceed the minimum string length.
        // The following solution is O(n^2), this can be improve.
        for ($i = 0 ; $i < $minLen; $i++){
            $tmp = $sports[0][$i];
    
            foreach ($sports as $s){
                if($s[$i] != $tmp)
                    $flag = true;
            }
            if($flag)
                break;
            else
                $common .= $sports[0][$i];
        }
    
        print $common;
    

提交回复
热议问题