5 ms·
To me, the first good questions would be: 1. What language(s) does this function have to be callable from? 2. Can I write it in any language? Rather than “Is
by prirun 10y ago
To me, the first good questions would be:
1. What language(s) does this function have to be callable from?
2. Can I write it in any language?
Rather than “Is this client side or server side JavaScript?”
Considering that I have no idea how to use a regex for this, it was very strange to read that the interviewer expected _many_ people would use a regex. Made me feel like I missed a year of school or something.
For efficiency, only half of the string needs to be tested, not the whole thing. (Edit: I realized later that the posted JS does this too. It was not obvious at first because "end" is also changing.)
Since I never actually do these things, I thought it might be fun to code one. First I wrote the simple function, pal1(). Then I wondered if Python had a built-in string reverse function, so looked that up with Google and found that it didn't. It has a klunky reversed() iterator, but there was the obtuse s[::-1] post on Stack Overflow that runs fast, so added that as an alternative. And I had to lookup the __name__ line, because I forgot the syntax of that, even though I've been writing Python (HashBackup backup program) for 7 years!
import sys
# the straightforward way, char-by-char compare
def pal1(s):
slen = len(s)
slenm1 = slen - 1
for i in xrange(slen/2):
if s[i] != s[slenm1-i]:
return False
return True
# s[:-5] === "the last 5 (or fewer) characters of s"
# s[::] === s === s[start:end:incr], where start=0, end=len(s), and incr=1
# s[::-1] === reverse(s) == s[end:start:incr], where start=0, end=len(s), and incr=-1
def pal2(s):
return s == s[::-1]
# select which palindrome function to use
pal = pal1
# test with:
# 1. null string
# 2. single char (odd length)
# 3. double char string (even length)
if __name__ == '__main__':
if len(sys.argv) != 2:
print 'usage: pal <string>'
else:
s = sys.argv[1]
if pal(s):
print 'yep'
else:
print 'nope'