Leetcode挑战题——Repeated String Match

╰半橙微兮° 2022-06-07 13:05 235阅读 0赞

Repeated String Match

Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = “abcd” and B = “cdabcdab”.

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times (“abcdabcd”).

Note:
The length of A and B will be between 1 and 10000.

  1. <?php
  2. $str1 = "abcd";
  3. $str2 = "cdabcdab";
  4. function repeatedStringMatch($str1,$str2,$num = 1,$a = ''){
  5. $str1_len = strlen($str1);
  6. $str2_len = strlen($str2);
  7. //判断字符串是否符号要求
  8. if(!in_array($str1_len, range(1, 10000)) || !in_array($str2_len, range(1, 10000))){
  9. return 'Invalid String!';
  10. }
  11. if($num == 1) $a = $str1;
  12. if(strstr($str1,$str2)){
  13. return $num;
  14. }elseif($str1_len > 2*$str2_len && strstr($str1,$str2) === false){
  15. return -1;
  16. }else{
  17. $str1 .= $a;
  18. return repeatedStringMatch($str1,$str2,++$num,$a);//递归调用函数,累加重复数,注意这里不能用$num++
  19. }
  20. }
  21. echo repeatedStringMatch($str1,$str2);
  22. ?>

结果:3

若有不对之处,希望各位批评指正,谢谢!

发表评论

表情:
评论列表 (有 0 条评论,235人围观)

还没有评论,来说两句吧...

相关阅读