We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Hello, I still need to learn more about string splicing so I can understand other solutions. I have my own solution which passes test cases but was wondering if someone could show me a better way to handle this line I wrote that is bothering me: if s[i + 1] == s[j] and s[i + 2] == s[j - 1]:
Before I added that, I built the function based off of my own string I made "rbacecar", and my logic on paper was basically this: 1. take off "r" from both sides of the string since they match 2. "b" and "a" don't match now. So, if we look just beyond "b", we see "a", which is a match. That means "b" is the problem.
HOWEVER, that doesn't work with strings like "fcwnnwcwf" or any string with more repetition in the letter choices. So, I added "and s[i + 2] == s[j - 1]" to my line with "if s[i + 1] == s[j]" so my function would check a little farther beyond. However, I don't think that's ideal.
defpalindromeIndex(s):# beginningi=0# endj=len(s)-1# default result is -1 (is palindrome)result=-1forcinrange(len(s)//2):# if current beginning is same as current end# passifs[i]==s[j]:pass# else, increment i up to "pass" over # potential problem character and keep # j the sameelse:# if current i is same as current j,# the issue must be on the left side# so return iifs[i+1]==s[j]ands[i+2]==s[j-1]:result=ireturnresult# else, the issue must be with j sideelse:result=jreturnresulti+=1j-=1returnresul
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Palindrome Index
You are viewing a single comment's thread. Return to all comments →
Hello, I still need to learn more about string splicing so I can understand other solutions. I have my own solution which passes test cases but was wondering if someone could show me a better way to handle this line I wrote that is bothering me: if s[i + 1] == s[j] and s[i + 2] == s[j - 1]: Before I added that, I built the function based off of my own string I made "rbacecar", and my logic on paper was basically this: 1. take off "r" from both sides of the string since they match 2. "b" and "a" don't match now. So, if we look just beyond "b", we see "a", which is a match. That means "b" is the problem. HOWEVER, that doesn't work with strings like "fcwnnwcwf" or any string with more repetition in the letter choices. So, I added "and s[i + 2] == s[j - 1]" to my line with "if s[i + 1] == s[j]" so my function would check a little farther beyond. However, I don't think that's ideal.