题目如下:
废话不多说,直接走代码:
<?php
//词根字典
$dict = ['cat','bat','ca','rat'];//为了满足题目使用最短的词根来替换的要求,特地多了个ca
//此处运用冒泡排序的主要目的是为了解决当一个衍生词有多个词根时,用后面的短词根替换前面的短词根,就满足了题目使用最短的词根来替换的要求了。
$dict = maopao($dict);//冒泡降序处理
//代替换处理的句子,注意句中的衍生词cattle就有2个词根了,cat和ca,我们应取最短的ca
$sentence = ' hello, the cattle was rattled by the battery ';
//调用替换词根函数,输出句子
echo '替换前:'.$sentence;
echo '<br>';
echo '替换后:'.replace_root($dict,$sentence);
//替换词根
function replace_root($dict,$sentence){
//判断输入的参数格式是否正确
if(!is_array($dict) || !is_string($sentence)) return '参数格式不对!';
//判断词根字典长度是否符合要求
if(count($dict) < 1 || count($dict) > 1000) return '词根字典长度不符合要求!';
//去掉字符串左右两边的空格
$trim_sentence = trim($sentence);
//去掉没两个单词之间多余的空格,只空一格
$greg_sentence = preg_replace("/\s+/", ' ', $trim_sentence);
//把字符串转换成数组
$sentence_array = explode(' ',$greg_sentence);
//判断句子词数是否符合要求
$sentence_length = $sentence_array;
if(count($sentence_length) < 1 || count($sentence_length) > 1000) return '句子词数不符合要求!';
foreach ($dict as $key => $val) {
//判断字典的词根长度是否符合要求
$root_length = strlen(trim($val));
if($root_length < 1 || $root_length > 100) return '词根长度不符合要求!';
foreach ($sentence_array as $k => &$v) {
//判断句子中单词的长度是否符合要求
$word_length = strlen($v);
if($word_length > 1000) return '句子中单词的长度不符合要求!';
if(strpos($v, $val) === 0) $v = $val;//如果恒等于0,即居于句首,说明是该衍生词具有该词根
}
}
//把数组转换成字符串
$replace_sentence = implode(' ', $sentence_array);
return $replace_sentence;
}
//根据元素长度进行降序的冒泡排序算法
function maopao($dict){
if(!is_array($dict) || count($dict) < 1) return '参数不对!';
for($i=0;$i<count($dict)-1;$i++ ){
for($j=0;$j<count($dict)-1-$i;$j++){
if(strlen($dict[$j]) < strlen($dict[$j+1])){
$tmp = $dict[$j];
$dict[$j] = $dict[$j+1];
$dict[$j+1] = $tmp;
}
}
}
return $dict;
}