PHP版今日头条算法面试题(持续更新)

1,现在有一个字符串,你要对这个字符串进行 n 次操作,每次操作给出两个数字:(p, l) 表示当前字符串中从下标为 p 的字符开始的长度为 l 的一个子串。你要将这个子串左右翻转后插在这个子串原来位置的正后方,求最后得到的字符串是什么。字符串的下标是从 0 开始的,你可以从样例中得到更多信息。

每组测试用例仅包含一组数据,每组数据第一行为原字符串,长度不超过 10 ,仅包含大小写字符与数字。接下来会有一个数字 n 表示有 n 个操作,再接下来有 n 行,每行两个整数,表示每次操作的(p , l)。

保证输入的操作一定合法,最后得到的字符串长度不超过 1000。



实现代码:

<?php

class TestKeenSting{
    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;









  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值