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.
以下是我们可以检查一个传递的字符串是否为回文的方法:
- 使用原生方法
- 通过反转字符串
- 使用split()、reverse()和join()方法
方法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()方法
另一种方法是通过最短的方式,使用split()、reverse()和join()方法。
- 将字符字符串分割成多个字符(目前未排序)。
- 使用reverse()方法按字母顺序颠倒所有字符。
- 然后用join()方法将字符串中的所有字符(现在已排序)连接起来。
示例: 下面是以上方法的实现:
// JavaScript code in order to check string palindrome...
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
极客教程