这是一个 C++ 实现:
sourceCpp('
bool isPalindrome(String x) {
std::string y(x);
int n = y.size();
for(int i = 0; i < n / 2; ++i) {
if (y[i] != y[n - i - 1]) return false;
}
return true;
}
')
它也不适用于非 ASCII 字符串,但它比纯 R 解决方案快 10 倍:
library(microbenchmark)
options(digits = 3)
is.palindrome <- function (word) {
identical(word, paste(rev(strsplit(word, "")[[1]]), collapse=""))
}
x <- paste(letters, rev(letters), collapse = "")
y <- paste("a", x)
microbenchmark(
is.palindrome(x),
isPalindrome(x),
is.palindrome(y),
isPalindrome(y)
)
# Unit: microseconds
# expr min lq median uq max neval
# is.palindrome(x) 24.62 25.99 27.14 28.29 36.38 100
# isPalindrome(x) 2.38 2.68 2.82 3.58 4.03 100
# is.palindrome(y) 24.68 26.44 27.78 28.46 80.94 100
# isPalindrome(y) 2.33 2.67 3.41 3.64 33.60 100