思路1:把A去重得到A1,B去重得到B1,然后對A1,B1分別進(jìn)行排序,然后遍歷較短的字符串的每個字符是否存在于較長的字符串中,存在則輸出問題:1.思路很簡單,基本大家都會這么考慮,但是面試的時候就沒有亮點(diǎn)了思路2:假設(shè)AB串只包含小寫(其實(shí)無所謂),那么創(chuàng)建一個數(shù)組,數(shù)組的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 就是為了區(qū)分 stemp中的原來的1 是 $str1中設(shè)置的 $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;?>
今天隨便瀏覽網(wǎng)頁的時候又發(fā)現(xiàn)了這篇文章(一次谷歌面試趣事)
我想起來了 思路二出自這篇文章。
新聞熱點(diǎn)
疑難解答