如何在JavaScript中检查传递的字符串是否为回文
在本文中,我们给定一个字符串,我们的任务是判断字符串是否为回文。回文是一系列数字、字符串或字母,当从右向左和从左向右阅读时完全匹配,或产生相同的字符序列。简单地说,当数字字符串或字符被翻转并仍然提供与原始数字或字符相同的结果时。
Example:
Input : "race"
Output : passed string is not a palindrome
Explanation : if we write "race" in reverse that is "ecar" it not
matches with first string so it is not a palindrome.
Example 2:
Input : "hellolleh"
Output : passed string is palindrome.
方法1: 在此方法中,我们使用以下步骤。
- 首先,我们以正向和反向方向遍历字符串。
- 检查所有正向和反向字符是否匹配,并返回true。
- 如果所有正向和反向字符都不匹配,则返回false。
- 如果返回true,则它是一个回文。
示例: 此示例演示了上述方法的使用。
// function that check str is palindrome or not
function check_palindrome(str) {
let j = str.length - 1;
for (let i = 0; i < j / 2; i++) {
let x = str[i];//forward character
let y = str[j - i];//backward character
if (x != y) {
// return false if string not match
return false;
}
}
/// return true if string is palindrome
return true;
}
//function that print output if string is palindrome
function is_palindrome(str) {
// variable that is true if string is palindrome
let ans = check_palindrome(str);
//condition checking ans is true or not
if (ans == true) {
console.log("passed string is palindrome ");
}
else {
console.log("passed string not a palindrome");
}
}
// test variable
let test = "racecar";
is_palindrome(test);
输出:
passed string is palindrome.
方法2: 另一种方法是将字符串反转并检查初始字符串是否与反转字符串匹配。
按照以下步骤进行:
- 初始化一个变量reverse_str,用于存储传递字符串的反转。
- 将字符串与reverse_str进行比较。
- 如果匹配,则是一个回文。
- 否则,字符串不是一个回文。
示例: 此示例演示了上述方法的使用。
// function to reverse the string
function reverse(str) {
// variable holds reverse string
let rev_str = "";
for (let i = str.length - 1; i >= 0; i--) {
rev_str += str[i];
}
// return reverse string
return rev_str;
}
// function checking string is palindrome or not
function is_palindrome(str) {
reverse_str = reverse(str);
// condition checking if reverse str is
// same as string it is palindrome
// else not a palindrome
if (reverse_str === str) {
console.log("passed string is palindrome ");
}
else {
console.log("passed string is not palindrome")
}
}
let test = "hellolleh";
is_palindrome(test);
输出:
passed string is palindrome.
方法3: 另一种方法是使用split()、reverse()和join()方法进行最短的方法。
- 将字符的字符串分成几个不同的字符(目前尚未排序)。
- 使用reverse()方法按字母顺序反转字符串的所有字符。
- 然后应用join()方法以将字符串的所有字符(现在已排序)连接在一起。
实例: 下面是上述方法的实现:
// JavaScript代码以检查字符串是否为回文...
let checkPalindrome = (stringg) => {
return stringg === stringg.split("").reverse().join("");
};
console.log("Is Palindrome? : " + checkPalindrome("noon"));
console.log("Is Palindrome?: " + checkPalindrome("apple"));
输出:
Is Palindrome? : true
Is Palindrome?: false
阅读更多:JavaScript 教程