查看: 1510|回复: 0

[PHP代码] PHP常见几道算法题目解析

发表于 2018-4-19 08:04:53

图片描述
第一题:
$a = '&&29&&&&&yy3&&';
$s = '&&';
function strToArr($a,$s){
$n = strlen($s);
$j = 0;
$data = array();
for($i=0;$i if(substr($a,$i,$n)==$s){
if($i==0){
$data[$j] = '';
$j++;
$i += $n-1;
continue;
}else if($i==(strlen($a)-$n)){
$j++;
$data[$j] = '';
$i += $n-1;
continue;
}else if(substr($a,$i+$n,$n)==$s){
$j++;
$data[$j] = '';
$i += $n-1;
continue;
}else{
$j++;
$i += $n-1;
continue;
}
}else{
if(!isset($data[$j]))
$data[$j] = '';
$data[$j] .= $a[$i];
}

  1. }
  2. return $data;
复制代码

}
echo '

';
echo '字符串1:'.$a;
echo '分割符:'.$s;
var_dump(strToArr($a,$s));
echo '
';
echo '
';
$a = 'yyy29yyy&&yyy3&&';
$s = 'yyy';
echo '字符串2:'.$a;
echo '分割符:'.$s;
var_dump(strToArr($a,$s));
echo '
';
?>
页面输出
字符串1:&&29&&&&&yy3&&分割符:&&array(5) {
[0]=>
string(0) ""
1=>
string(2) "29"
[2]=>
string(0) ""
[3]=>
string(4) "&yy3"
[4]=>
string(0) ""
}
字符串2:yyy29yyy&&yyy3&&分割符:yyyarray(4) {
[0]=>
string(0) ""
1=>
string(2) "29"
[2]=>
string(2) "&&"
[3]=>
string(3) "3&&"
}

$a = array('11','55','&&','ee');
$s = '&&';
function arrToStr($a,$s){
$str = '';
foreach($a as $k=>$v){
$str .= $v.$s;
}
$str = substr($str,0,-2);
return $str;
}
$str = arrToStr($a,$s);
echo '

';
echo '数组:';
var_dump($a);
echo '拼接符:'.$s;
var_dump($str);
echo '
';
?>
页面输出:
数组:array(4) {
[0]=>
string(2) "11"
1=>
string(2) "55"
[2]=>
string(2) "&&"
[3]=>
string(2) "ee"
}
拼接符:&&string(14) "11&&55&&&&&&ee"

第二题:
$n = 100;
function getMaxNum($n){
for($n;$n>=2;$n--){
$flag = '';
for($i=2;$i<$n;$i++){
if(($n%$i==0)){
$flag = 1;
continue ;
}
}
if(!$flag){
return $n;
}
}
return false;
}
$num = getMaxNum($n);
var_dump($num);

?>
页面输出:
int(97)
第三题:
$a = [0,1,2,3,4,5,6,7,8,9,6];
function getRepeat($a){
$data = [];
foreach($a as $k=>$v){
if(isset($data[$v]) && $data[$v]==$v){
return $v;
}
$data[$v] = $v;
}
return false;
}
$num = getRepeat($a);
var_dump($num);

?>
页面输出:
int(6)
第四题:
function king($n,$m) {
$people = range(1,$n);
$i = 0;
while(count($people) > 1) {
if(($i+1)%$m == 0) {
unset($people[$i]);
} else {
//如果不是制定的数字直接往后面追加 这样可以一直进行下去
array_push($people,$people[$i]);
unset($people[$i]);
}
$i++;
}
return current($people);
}
$n = 8;$m = 4;
$king = king($n,$m);
print_r($king);
页面输出:
6
第五题:
字符串求子集问题 需要进一步改善



回复

使用道具 举报