I was practicing on leetcode question #5. What really puzzles me is the huge runtime difference between C++ (~20ms) and Python (~1000ms) here.
I understand that Python is an interpreted language so in general it is slower than C++. But here C++ being 50 times faster than Python is beyond my understanding. Both programs use the same algorithm so it's not that. Is it due to how strings are implemented in C++ and Python?
C++
class Solution {
public:
string longestPalindrome(string s) {
if(s.size() == 0) return "";
int length = 1, index = 0, subOddLength = 1, subEvenLength = 1, subLength = 1;
for(int i = 1; i < s.size(); ++i){
subOddLength = palindromeLength(s, i, i);
subEvenLength = palindromeLength(s, i - 1, i);
subLength = max(subOddLength, subEvenLength);
if(subLength > length){
length = subLength;
index = i - subLength / 2;
}
}
return s.substr(index, length);
}
private:
int palindromeLength(const string &s, int l, int r){
int n = s.size();
while(l >= 0 & r < n){
if(s[l] != s[r]) break;
l--; r++;
}
l++; r--;
return r - l + 1;
}
};
Python
class Solution:
def longestPalindrome(self, s: str) -> str:
def palindrome_length(l, r):
while l >= 0 and r < len(s):
if s[l] != s[r]: break;
l -= 1; r += 1
l += 1; r -= 1
return r - l + 1
length, index = 1, 0
for i in range(1, len(s)):
odd_len = palindrome_length(i, i)
even_len = palindrome_length(i - 1, i)
sub_len = max(odd_len, even_len)
if sub_len > length:
length, index = sub_len, i - sub_len // 2
return s[index : index + length]