This time I will show you how to operate js to find the longest palindrome string in string, and how to operate js to find the longest palindrome string in a stringNotes What are they? Here are actual cases. Let’s take a look.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>回文</title> <link rel="stylesheet" href=""> </head> <body> <script type="text/javascript"> function longestPalindrome(str){ let palindromeStr=""; //记录最长回文串 let tempPalindrome=""; //记录当前回文串 for(let i=0;i<str.length;i++){ //i记录当前遍历字符串的开始位置,循环依次向后遍历 tempPalindrome=""; //每次新的一轮开始时,将临时记录回文串的变量清空 for(let j=i;j<str.length;j++){ //每次开始循环是以当前i所在的下标位置为开始遍历字符串的起始位置,直到遍历到结束位置 tempPalindrome+=str.charAt(j); //逐个增加字符串的长度 if(isPalindrome(tempPalindrome) && tempPalindrome.length>palindromeStr.length){ //将当前的字符串传入isPalindrome进行回文判断,如果是回文串,则判断当前回文串长度是否大于之前记录的最长回文串的长度,如果大于之前的回文串,则更新之前的记录即可 palindromeStr=tempPalindrome; //更新回文串 } } } return palindromeStr; //返回最终的最长的回文串 } function isPalindrome(s){ //判断是否为回文串 let rev=s.split('').reverse().join(''); //字符串逆转操作 return rev===s; } //测试 console.log(longestPalindrome("ddabbade"));//输出dabbad </script> </body> </html>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
JS implements data patterns within statistical strings
How to use JS strict mode in projects
The above is the detailed content of How to use js to find the longest palindrome string in a string. For more information, please follow other related articles on the PHP Chinese website!