String manipulations, a fidelity palindrome

Allow categorization of this for PHP only.

So, yesterday I had an interview for the senior role of a software developer. I don’t remember this question very well, but I try to write it the way I remember.

Question

Write a function that takes a string as input and returns true if passed, false if not.

Requirements; (as far as I remember) - Only one type of input (string).
- The String parameter must be passed by reference.
- There is no variable inside the function, it means that if the pair is called $ str manipulation, then you need to do this, I did not like using the second variable to set reverseStr, etc.
- No cycle of each character in the line, he specifically said, so as not to go through each character in the line.
- There is no PHP built-in function, I think it was ok with (strlen)

My answer (no, he didn’t like it)

$str = 'this is testing'; $length = strlen($str); $reverseStr = ''; for($i=$length-1; $i>=0; $i--) { $reverseStr .= $str[$i]; } 

So, although this does work a little, he didn’t want me to go through each character to get reverseStr. I guess I needed to think of a recursive solution, get the last character of the string and index etc.etc. but I think about it as I write this, too late!

What do you guys think?

+4
source share
3 answers

the question is not entirely clear .. but if you want to check if the string is a palindrome:

 function is_palindrome ($str){ if(strlen($str)==0){return true;} if($str[0]==$str[strlen($str)-1]){ return true and is_palindrome(substr($str, 1, strlen($str)-2)); }else{ return false; } } 
+4
source

I think it works. tested. Although it has internal variables.

  function is_palindrome( &$str ) { $i = $j = 0; while( isset( $str[++$j] ) ) {}; while( $i < --$j ) { if( $str[$i++] !== $str[$j] ) return FALSE; } return TRUE; } 
0
source

So, he said that “he doesn’t make his way through each character,” but he said nothing about going through half of them? [evil laugh]

 function is_palindrome(&$str) { for($i = 0; $i < strlen($str) / 2; $i++) { if ($str[$i] != $str[strlen($str)-1-$i]) return false; } return true; } 

He said that there is no variable in the $str manipulation function, but of course the iterator is ok? (well, except for the "no looping" rule ...)

 is_palindrome('abcdcba'); // odd length, returns true is_palindrome('abcddcba'); // even length, returns true is_palindrome('abc'); // not a palindrome, returns false 

I know, I know, it compresses the letter of demands, not the spirit of them.

0
source

Source: https://habr.com/ru/post/1445809/


All Articles