检查回文数/字符串的奇偶长度是否是个好主意?大多数我找到的片段都没有执行这个基本测试。如果长度是偶数,它不能是回文吧?
if len(var) % 2 != 0:
# could be a palindrome, continue...
else:
break
还是直接比较第一个和最后一个数字/字母更好(即更快)?
编辑:好的,这是个愚蠢的问题,我应该再想一次! :)
检查回文数/字符串的奇偶长度是否是个好主意?大多数我找到的片段都没有执行这个基本测试。如果长度是偶数,它不能是回文吧?
if len(var) % 2 != 0:
# could be a palindrome, continue...
else:
break
还是直接比较第一个和最后一个数字/字母更好(即更快)?
编辑:好的,这是个愚蠢的问题,我应该再想一次! :)
检查回文最简单的方法是将字符串与它的反转进行比较:
def ispalindrome(s):
return s == s[::-1]
这里使用了带有负步长的扩展切片,以反向遍历 s
并获取其反转结果。
return s == s[::-1]
- tgraybaab = 回文且长度为4,且长度为偶数
试试这个:
is_palindrome = lambda s : all(s1==s2 for s1,s2 in zip(s[:len(s)/2],s[-1:-(len(s)+1)/2:-1]))
简单情况:aa。
更复杂的情况:aaaa。
等等。
function isStrPermutationOfPalindrome(_str) { // backward = forward
var isPermutationOfPalindrome = true;
var _strArr = [..._str];
var _strArrLength = _strArr.length;
var counterTable = getCharsTabularFrequencies(_str);
var countOdd = 0;
var countEven = 0;
for (let [ky, val] of counterTable) {
if (val % 2 == 0) {
countEven = countEven + 1;
} else {
countOdd = countOdd + 1;
}
}
if (_strArrLength % 2 == 0) {
//Even count of all characters,otherwise false.
//so can not have a character with odd count.
if (countOdd != 0) {
isPermutationOfPalindrome = false;
}
} else {
//Odd count of 1 character
//so not all chars with even count, only one char of odd count.
if (countOdd > 1 || countOdd == 0) { //no odd, or more than one odd [ only one odd should be to return true]
isPermutationOfPalindrome = false;
}
}
return isPermutationOfPalindrome;
}
function getCharsTabularFrequencies(str) {
str = str.toLowerCase();
var arr = Object.assign([], str);
var oMap = new Map();
var _charCount = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === ' ') {
continue;
}
_charCount = 0;
for (let j = 1; j < arr.length; j++) {
{
if (arr[i] === arr[j]) {
_charCount = _charCount + 1;
}
}
}
if (i == 0)
_charCount = _charCount + 1;
if (!oMap.has(arr[i]))
oMap.set(arr[i], _charCount)
}
return oMap;
}
let _str = 'tactcoapapa';
console.log("Is a string of '" + _str + "' is a permutation of a palindrome ? ANSWER => " + isStrPermutationOfPalindrome(_str));
n=raw_input("Enter a string==>")
n=int(n)
start=0
term=n
while n>0:
result=n%10
start=start*10+result
n=n/10
print start
if term==start:
print "True"
else:
print "False"