面試題之算法集錦,試題算法集錦
思路1:
把A去重得到A1,B去重得到B1,然後對A1,B1分別進行排序,然後遍歷較短的字符串的每個字符是否存在於較長的字符串中,存在則輸出
問題:
1.思路很簡單,基本大家都會這麼考慮,但是面試的時候就沒有亮點了
思路2:
假設AB串只包含小寫(其實無所謂),那麼創建一個數組,數組的key為a->z,value都是0;
<?php
function stringToChar($str,$num=1,$tmp=null){
if(empty($tmp)){
$tmp=array('a'=>0,'b'=>0,'c'=>0,'d'=>0,'e'=>0,'f'=>0,'g'=>0,'h'=>0,'i'=>0,'j'=>0,'k'=>0,'l'=>0,'m'=>0,'n'=>0,'o'=>0,'p'=>0,'q'=>0,'r'=>0,'s'=>0,'t'=>0,'u'=>0,'v'=>0,'w'=>0,'x'=>0,'y'=>0,'z'=>0);
}
$arr_temp=str_split($str,1);
foreach($arr_temp as $v){
if($tmp[$v]<$num){
$tmp[$v]+=$num;
}
}
return $tmp;
}
function getStringIntersect($str1, $str2){
$temp=stringToChar($str1,1);
//$str2的$num用2 就是為了區分 stemp中的原來的1 是 $str1中設置的
$temp=stringToChar($str2,2,$temp);
$result='';
foreach ($temp as $key => $value) {
if($value===3){
$result.=$key;
}
}
return $result;
}
$A="common";//"hello";
$B="month";//"jeesite";
$result=getStringIntersect($A, $B);
echo $result;
?>
今天隨便浏覽網頁的時候又發現了這篇文章(一次谷歌面試趣事)
我想起來了 思路二出自這篇文章。