Appearance
回文字符串 / isPalindrome
题目描述
从左往右读和从右往左读是一样的字符串,则认为是一个回文字符串。
Input: ABCDCBA
Ouput: true
Input: EFEF
Ouput: false
Input: ''
Output: true
Code
function isPalindrome(str) {
if (str === '') return true;
const len = str.length;
let left = 0;
let right = len - 1;
while (left < right) {
if (str[left] !== str[right]) {
return false;
}
left++;
right--;
}
return true;
}
Test Cases
const { isPalindrome } = require('../docs/algo/string/palindrome');
describe('isPalindrome', () => {
it('case1', () => {
expect(isPalindrome('ABCDCBA')).toBeTruthy();
});
it('case2', () => {
expect(isPalindrome('EFEF')).toBeFalsy();
});
it('Test empty string', () => {
expect(isPalindrome('')).toBeTruthy();
});
});
jest --testNamePattern=isPalindrome