检查JavaScript中回文的两种方法

本文基于Free Code Camp基本算法脚本“ Palindromes检查”。

palindrome是一个单词,词组,数字或其他顺序向后或向前读取的字符。“palindrome”一词最早是由英国剧作家本·琼森(Ben Jonson)在17世纪创造的,其起源是希腊语的palin(“again”)和dromos(“ way,direction”)。— src.维基百科

在本文中,我将解释两种方法,一种是使用内置函数,另一种是使用for循环。

算法挑战

如果给定的字符串是回文,则返回true。否则,返回false。

回文是指向前或向后以相同方式拼写的单词或句子,而忽略了标点,大小写和空格。

注意:您需要删除所有非字母数字字符(标点,空格和符号),并将所有内容都转换为小写以检查palindrome。

我们将传递各种格式的字符串,例如“ racecar”,“ RaceCar”和“ race CAR”。

function palindrome(str) {
     
  return true;
}
palindrome("eye");

提供的测试用例

  • palindrome(“race car”)返回true
  • palindrome(“not a palindrome”)返回false
  • palindrome(“A man, a plan, a canal. Panama”)返回true
  • palindrome(“neverodd or even”)返回true
  • palindrome(“nope”)返回false
  • palindrome(“almostomla”)返回false
  • palindrome(“My age is 0, 0 si ega ym.”)返回true
  • palindrome(“1 eye for of 1 eye.”)返回false
  • palindrome(“0_0(: /-\ :) 0–0”)返回true

我们需要哪个正确表达式通过最后一个测试用例?

正确表达式是用于匹配字符串中字符组合的模式。

当搜索匹配项不仅仅需要直接匹配项时,该模式将包含特殊字符。

To pass the last test case, we can use two Regular Expressions:

/[^A-Za-z0–9]/g  or

/[\W_]/g

\ W删除所有非字母数字字符:

  • \ W匹配任何非单词字符
  • \ W等效于[^ A-Za-z0–9_]
  • \ W匹配括号中未包含的任何内容

这意味着什么?

[^A-Z] matches anything that is not enclosed between A and Z

[^a-z] matches anything that is not enclosed between a and z

[^0-9] matches anything that is not enclosed between 0 and 9

[^_] matches anything that does not enclose _

但是在我们的测试案例中,我们需要palindrome(“ 0_0(:/-\ :)0–0 ”)返回true,这意味着必须匹配“ _(:/-\:)– ”。

我们将需要添加“ _ ”以通过此特定测试用例。

We now have “\W_”

我们还需要添加g标志进行全局搜索。

We finally have “/[\W_]/g”
  • / [\ W _] / g用于纯粹的演示目的,以显示RegExp的工作方式。/ [^ A-Za-z0–9] / g是最容易选择的RegExp 。

1.检查具有内置功能的回文

对于此解决方案,我们将使用几种方法:

  • toLowerCase()的方法返回调用字符串值转换为小写。
  • replace()的方法返回的部分或由替换替换模式的所有匹配一个新的字符串。我们将使用我们刚才创建的RegExp之一。
  • split()的方法通过分离串分成子串分割字符串对象到字符串数组。
  • reverse()的方法在当前位置倒转的阵列。第一个数组元素变为最后一个,最后一个数组变为第一个。
  • join()的方法连接到一个字符串数组的所有元素。
function palindrome(str) {
     
  // Step 1. Lowercase the string and use the RegExp to remove unwanted characters from it
  var re = /[\W_]/g; // or var re = /[^A-Za-z0-9]/g;
  
  var lowRegStr = str.toLowerCase().replace(re, '');
  // str.toLowerCase() = "A man, a plan, a canal. Panama".toLowerCase() = "a man, a plan, a canal. panama"
  // str.replace(/[\W_]/g, '') = "a man, a plan, a canal. panama".replace(/[\W_]/g, '') = "amanaplanacanalpanama"
  // var lowRegStr = "amanaplanacanalpanama";
     
  // Step 2. Use the same chaining methods with built-in functions from the previous article 'Three Ways to Reverse a String in JavaScript'
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  // lowRegStr.split('') = "amanaplanacanalpanama".split('') = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]
  // ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].reverse() = ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"]
  // ["a", "m", "a", "n", "a", "p", "l", "a", "n", "a", "c", "a", "n", "a", "l", "p", "a", "n", "a", "m", "a"].join('') = "amanaplanacanalpanama"
  // So, "amanaplanacanalpanama".split('').reverse().join('') = "amanaplanacanalpanama";
  // And, var reverseStr = "amanaplanacanalpanama";
   
  // Step 3. Check if reverseStr is strictly equals to lowRegStr and return a Boolean
  return reverseStr === lowRegStr; // "amanaplanacanalpanama" === "amanaplanacanalpanama"? => true
}
 
palindrome("A man, a plan, a canal. Panama");

没有注释:

function palindrome(str) {
     
  var re = /[\W_]/g;
  var lowRegStr = str.toLowerCase().replace(re, '');
  var reverseStr = lowRegStr.split('').reverse().join(''); 
  return reverseStr === lowRegStr;
}
palindrome("A man, a plan, a canal. Panama");

2.用FOR循环检查回文
半索引(len / 2)在处理大字符串时有好处。我们检查每个部分的结尾,然后将FOR循环内的迭代次数除以2。

function palindrome(str) {
     
 // Step 1. The first part is the same as earlier
 var re = /[^A-Za-z0-9]/g; // or var re = /[\W_]/g;
 str = str.toLowerCase().replace(re, '');

 // Step 2. Create the FOR loop
 var len = str.length; // var len = "A man, a plan, a canal. Panama".length = 30
 
 for (var i = 0; i < len/2; i++) {
     
   if (str[i] !== str[len - 1 - i]) {
      // As long as the characters from each part match, the FOR loop will go on
       return false; // When the characters don't match anymore, false is returned and we exit the FOR loop
   }
   /* Here len/2 = 15
      For each iteration: i = ?    i < len/2    i++    if(str[i] !== str[len - 1 - i])?
      1st iteration:        0        yes         1     if(str[0] !== str[15 - 1 - 0])? => if("a"  !==  "a")? // false
      2nd iteration:        1        yes         2     if(str[1] !== str[15 - 1 - 1])? => if("m"  !==  "m")? // false      
      3rd iteration:        2        yes         3     if(str[2] !== str[15 - 1 - 2])? => if("a"  !==  "a")? // false  
      4th iteration:        3        yes         4     if(str[3] !== str[15 - 1 - 3])? => if("n"  !==  "n")? // false  
      5th iteration:        4        yes         5     if(str[4] !== str[15 - 1 - 4])? => if("a"  !==  "a")? // false
      6th iteration:        5        yes         6     if(str[5] !== str[15 - 1 - 5])? => if("p"  !==  "p")? // false
      7th iteration:        6        yes         7     if(str[6] !== str[15 - 1 - 6])? => if("l"  !==  "l")? // false
      8th iteration:        7        yes         8     if(str[7] !== str[15 - 1 - 7])? => if("a"  !==  "a")? // false
      9th iteration:        8        yes         9     if(str[8] !== str[15 - 1 - 8])? => if("n"  !==  "n")? // false
     10th iteration:        9        yes        10     if(str[9] !== str[15 - 1 - 9])? => if("a"  !==  "a")? // false
     11th iteration:       10        yes        11    if(str[10] !== str[15 - 1 - 10])? => if("c" !==  "c")? // false
     12th iteration:       11        yes        12    if(str[11] !== str[15 - 1 - 11])? => if("a" !==  "a")? // false
     13th iteration:       12        yes        13    if(str[12] !== str[15 - 1 - 12])? => if("n" !==  "n")? // false
     14th iteration:       13        yes        14    if(str[13] !== str[15 - 1 - 13])? => if("a" !==  "a")? // false
     15th iteration:       14        yes        15    if(str[14] !== str[15 - 1 - 14])? => if("l" !==  "l")? // false
     16th iteration:       15        no               
    End of the FOR Loop*/
 }
 return true; // Both parts are strictly equal, it returns true => The string is a palindrome
}

palindrome("A man, a plan, a canal. Panama");

没有注释:

function palindrome(str) {
     
 var re = /[^A-Za-z0-9]/g;
 str = str.toLowerCase().replace(re, '');
 var len = str.length;
 for (var i = 0; i < len/2; i++) {
     
   if (str[i] !== str[len - 1 - i]) {
     
       return false;
   }
 }
 return true;
}
palindrome("A man, a plan, a canal. Panama");

关注:Hunter网络安全 获取更多资讯
网站:bbs.kylzrv.com
CTF团队:Hunter网络安全
文章:Sonya Moisset
排版:Hunter-匿名者

你可能感兴趣的:(技术,javascript,安全,经验分享,其他,算法)