为什么C++比Python快得多?

2024-10-03 17:20:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我在练习leetcode问题5。真正困扰我的是C++(~20MS)和Python(~1000毫秒)之间的巨大运行时差异。p>

我理解Python是一种解释性语言,所以一般来说它比C++慢。但是这里C++比Python快50倍,这超出了我的理解。两个程序使用相同的算法,所以不是这样。是因为字符串是如何在C++和Python中实现的?p>

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]

Tags: sizestringindexlenreturniflengthclass