Javascript - Kiểm tra xem một chuỗi có phải là palindrome ?
Kiểm tra xem một chuỗi đã truyền có phải là palindrome hay không
Viết một hàm JavaScript để kiểm tra xem một chuỗi được truyền vào có phải là palindrome hay không?
Lưu ý: Một palindrome là từ, cụm từ đọc ngược lại như nhau, ví dụ: madam hoặc nurses
Ví dụ:
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<title>A passed string is palindrome or notlt;/title>
<script>
// Write a JavaScript function that checks whether a passed string is palindrome or not?
function check_Palindrome(str_entry){
// Change the string into lower case and remove all non-alphanumeric characters
var cstr = str_entry.toLowerCase().replace(/[^a-zA-Z0-9]+/g,'');
var ccount = 0;
// Check whether the string is empty or not
if(cstr==="") {
document.write("Nothing found!");
return false;
}
// Check if the length of the string is even or odd
if ((cstr.length) % 2 === 0) {
ccount = (cstr.length) / 2;
} else {
// If the length of the string is 1 then it becomes a palindrome
if (cstr.length === 1) {
document.write("Entry is a palindrome.");
return true;
} else {
// If the length of the string is odd ignore middle character
ccount = (cstr.length - 1) / 2;
}
}
// Loop through to check the first character to the last character and then move next
for (var x = 0; x < ccount; x++) {
// Compare characters and drop them if they do not match
if (cstr[x] != cstr.slice(-1-x)[0]) {
document.write("Entry is not a palindrome.");
return false;
}
}
document.write("The entry is a palindrome.");
return true;
}
check_Palindrome('madam');
check_Palindrome('nurses run');
check_Palindrome('fox');
</script>
</head>
<body>
</body>
</html>
hiepsiithml1
Lưu đồ thuật toán: