PHP版今日頭條演算法面試題(持續更新)
阿新 • • 發佈:2018-12-30
1,現在有一個字串,你要對這個字串進行 n 次操作,每次操作給出兩個數字:(p, l) 表示當前字串中從下標為 p 的字元開始的長度為 l 的一個子串。你要將這個子串左右翻轉後插在這個子串原來位置的正後方,求最後得到的字串是什麼。字串的下標是從 0 開始的,你可以從樣例中得到更多資訊。
每組測試用例僅包含一組資料,每組資料第一行為原字串,長度不超過 10 ,僅包含大小寫字元與數字。接下來會有一個數字 n 表示有 n 個操作,再接下來有 n 行,每行兩個整數,表示每次操作的(p , l)。
保證輸入的操作一定合法,最後得到的字串長度不超過 1000。
實現程式碼:
<?php classTestKeenSting{ private $str; public function __construct($str) { $this->str = $str; } public function run($orders) { foreach($orders as $item) { $this->execute($item[0],$item[1]); } return $this->str; } private function execute($pos,$length) { $len = strlen($this->str);if(($length-$pos) > $len) exit(1); else $tmp_str = substr($this->str,$pos,$length); $s1 = substr($this->str,0,$pos+$length); $s2 = substr($this->str,$pos+$length); $dest_str = $this->str_reverse($tmp_str); $this->str = $s1.$dest_str.$s2; } private function str_reverse($str) { $len= strlen($str); if($len%2 == 0) $times = $len/2; else $times = ($len-1)/2; for($i=0;$i<$times;$i++) { $t = $str[$len-1-$i]; $str[$len-1-$i] = $str[$i]; $str[$i] = $t; } return $str; } } $a = new TestKeenSting('ab'); $re = $a->run([[0,2],[1,3]]); echo $re;
2,你作為一名出道的歌手終於要出自己的第一份專輯了,你計劃收錄 n 首歌而且每首歌的長度都是 s 秒,每首歌必須完整地收錄於一張 CD 當中。每張 CD 的容量長度都是 L 秒,而且你至少得保證同一張 CD 內相鄰兩首歌中間至少要隔 1 秒。為了辟邪,你決定任意一張 CD 內的歌數不能被 13 這個數字整除,那麼請問你出這張專輯至少需要多少張 CD ?
每組測試用例僅包含一組資料,每組資料第一行為三個正整數 n, s, L。 保證 n ≤ 100 , s ≤ L ≤ 10000
實現程式碼:
<?php class TestKeenSting{ private $song_num; private $song_size; private $cd_size; public function __construct($n,$s,$l) { if($n>100 || $s>$l) exit('input error!'); $this->song_num = $n; $this->song_size = $s; $this->cd_size = $l; } public function run() { $cd_container = $this->calculate_single_cd(); return ceil($this->song_num/$cd_container); } private function calculate_single_cd() { //假設一張cd可以放n個 song_length+1 $n = floor($this->cd_size / ($this->song_size + 1)); //對剩餘空間做判斷 $gap = $this->cd_size - $n * ($this->song_size + 1); if($gap == $this->song_size)//剩餘空間是否剛好可以放一首歌 if($n!=12)//已經放了12首歌,不要這最後的一首 $n += 1; else if($n == 13) //如果之前就已經可以放13首,放棄一首 $n = 12; return $n; } } $a = new TestKeenSting(7,2,6); $re = $a->run(); echo $re;