Advertisement
VanessaShopping

Largest common end

Jan 31st, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.04 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: VanessaShopping
  5.  * Date: 31-Jan-17
  6.  * Time: 4:47 PM
  7.  */
  8.  
  9. $firstInput = trim(fgets(STDIN));
  10. $secondInput = trim(fgets(STDIN));
  11.  
  12. $firstArray = explode(" ", $firstInput);
  13. $secondArray = explode(" ", $secondInput);
  14.  
  15. $leftCount = 0;
  16. $rightCount = 0;
  17.  
  18. $firstCount = count($firstArray);
  19. $secondCount = count($secondArray);
  20. $count = 0;
  21. if ($firstCount >= $secondCount) {
  22.     $count = $secondCount;
  23. } else {
  24.     $count = $firstCount;
  25. }
  26. // check from left to right
  27. for ($i = 0; $i < $count; $i++) {
  28.     if ($firstArray[$i] == $secondArray[$i]) {
  29.         $leftCount++;
  30.     } else {
  31.         break;
  32.     }
  33. }
  34.  
  35. // check from right to left
  36. $reverseFirstArray = array_reverse($firstArray);
  37. $reverseSecondArray = array_reverse($secondArray);
  38. for ($i = 0; $i < $count; $i++) {
  39.     if ($reverseFirstArray[$i] == $reverseSecondArray[$i]) {
  40.         $rightCount++;
  41.     } else {
  42.         break;
  43.     }
  44. }
  45.  
  46. if ($leftCount >= $rightCount) {
  47.     echo $leftCount;
  48. } else {
  49.     echo $rightCount;
  50. }
  51.  
  52. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement