中英文模式阅读
中文模式阅读
英文模式阅读

Project 1 from JavaScript Algos and DS Certification.
项目1来自JavaScript Algos和DS Certification。

This is the blog version of my walkthrough. If you prefer video
这是我的演练的博客版本。如果您更喜欢视频here is the YouTube video link.

The Challenge {#thechallenge}

project-1-intro-screenshot

Write a function called
写一个叫做的函数palindrome that takes a string,
需要一个字符串,str. If
。如果str is a palindrome, return
是回文,回归true, otherwise return
,否则返回false.

What Is a Palindrome? {#whatisapalindrome}

A palindrome is a word that reads the same forwards and backwards. Some examples are
回文是一个向前和向后读取相同的词。一些例子是

  • Eye
  • Racecar
  • A Man, A Plan, A Canal -- Panama!

Whether you read these left-to-right or right-to-left, you get the same sequence of characters.
无论您是从左到右还是从右到左阅读,您都可以获得相同的字符序列。 We'll be ignoring punctuation like commas, periods, question marks, exclamation points, and casing.

Step 0 - Step Away from the Code {#step0stepawayfromthecode}

I like keeping this mind during any interview or problem I have to solve at work. Rushing into the code first is usually a losing strategy, because now you have to consider syntax while trying to solve the problem in your head.
我喜欢在工作中必须解决的任何面试或问题中保持这种想法。首先冲进代码通常是一种失败的策略,因为现在你必须在尝试解决问题时考虑语法。

Code should come last
代码应该是最后的

Don't let your nerves get the better of you. Instead of frantically hacking at a solution and elevating your blood pressure, take a deep breath and try to write it out on a whiteboard or in a notebook.
不要让你的神经变得更好。而不是疯狂地破解解决方案并提高血压,深呼吸并尝试在白板或笔记本上写出来。

Once you've thought out a solution, the code comes easy. All the hard work happens in your mind and notes, not on the keyboard.
一旦你想出了解决方案,代码就变得简单了。所有艰苦的工作都发生在你的思想和笔记中,而不是键盘上。

Step 1 - Equalize All Casing {#step1equalizeallcasing}

A palindrome is valid whether or not its casing reads the same forwards or backwards. So "Racecar" is valid even though it's technically spelt "racecaR" backwards.
无论其外壳是否向前或向后读取,回文都是有效的。所以"Racecar"是有效的,即使它在技术上拼写为"racecaR"向后。

To safeguard us against any casing issues, I'll add a comment saying we'll lowercase everything.
为了保护我们免受任何套管问题的影响,我将添加评论说我们将小写一切。

Here's my code so far (notice I wrote no real code yet).
到目前为止这是我的代码(注意我还没有编写真正的代码)。

function palindrome(str) {
  // 1) Lowercase the input
}



palindrome("eye");

Step 2 - Strip Non-Alphanumeric Characters {#step2stripnonalphanumericcharacters}

Just like the casing scenario, a palindrome is valid even if the punctuation and spaces aren't consistent back and forth.
就像套管场景一样,即使标点符号和空格来回不一致,回文也是有效的。

For example "A Man, A Plan, A Canal -- Panama!" is valid because we examine it without any marks or spaces. If you do that and lowercase everything, it becomes this.
例如"一个人,一个计划,一个运河 - 巴拿马!"是有效的,因为我们检查它没有任何标记或空格。如果你这样做并小写一切,那就变成了这个。

"A Man, A Plan, A Canal -- Panama!"

// lowercase everything
// strip out non-alphanumeric characters

"amanaplanacanalpanama"

Which reads the same forwards and backwards.
其中向前和向后读取相同的内容。

What does alphanumeric mean? {#whatdoesalphanumericmean}

It means "letters and numbers", so anything from a-z and 0-9 is an alphanumeric character. In order to properly examine our input non-alphanumeric characters (spaces, punctuation, etc) must go.
它的意思是"字母和数字",因此az和0-9中的任何内容都是字母数字字符。为了正确检查我们输入的非字母数字字符(空格,标点符号等)必须去。

Here's our updated pseudocode.
这是我们更新的伪代码。

function palindrome(str) {
  // 1) Lowercase the input
  // 2) Strip out non-alphanumeric characters
}



palindrome("eye");

Step 3 - Compare String to Its Reverse {#step3comparestringtoitsreverse}

Once our string's properly cleaned up, we can flip it around and see if it reads the same.
一旦我们的字符串被正确清理,我们可以翻转它,看看它是否相同。

I'm thinking a comparison along these lines
我正在考虑沿着这些方向进行比较

return string === reversedString

I'm using triple equals (
我正在使用三等于(===) for comparison in JavaScript. If the two strings are identical, it's a palindrome and we return
)用于JavaScript中的比较。如果两个字符串相同,则它是回文并且我们返回true! If not we return
!如果不是,我们回来false.

Here's our updated pseudocode.
这是我们更新的伪代码。

function palindrome(str) {
  // 1) Lowercase the input
  // 2) Strip out non-alphanumeric characters
  // 3) return string === reversedString
}



palindrome("eye");

Executing Step 1 - Lowercase {#executingstep1lowercase}

This is the easiest step. If you are unsure how to lowercase something in JavaScript, a quick Google search should lead to the
这是最简单的一步。如果您不确定如何在JavaScript中小写一些内容,那么快速Google搜索应该会导致toLowerCase method.
方法。

This is a method available on all string, so we can use it to lowercase our input before doing anything else.
这是一个可用于所有字符串的方法,因此我们可以在执行任何其他操作之前使用它来小写输入。

I'll store the lowercase version in a variable called
我将小写版本存储在一个名为的变量中alphanumericOnly because we're eventually going to remove alphanumeric characters too.
因为我们最终也会删除字母数字字符。

function palindrome(str) {
  // 1) Lowercase the input
  const alphanumericOnly = str.toLowerCase();
  
  // 2) Strip out non-alphanumeric characters
  // 3) return string === reversedString
}



palindrome("eye");

Executing Step 2 - Alphanumeric Only {#executingstep2alphanumericonly}

We'll have to dive a bit deeper here, as this is the toughest step. How exactly are we going to purify a string of its non-alphanumeric characters?
我们将不得不在这里深入探讨,因为这是最艰难的一步。我们究竟要如何净化一串非字母数字字符?

The .match method {#thematchmethod}

Just like
就像toLowerCase all strings support a method called
所有字符串都支持一个名为match. It takes a parameter indicating what character(s) you'd like to look for in a given string.
。它需要一个参数来指示您希望在给定字符串中查找哪些字符。

Let's use my name as an example.
我们以我的名字为例。

myName = 'yazeed';

myName.match('e');
// ["e", index: 3, input: "yazeed", groups: undefined]

As you can see
如你看到的.match returns an array with some information. The part we care about is the first element,
返回包含一些信息的数组。我们关心的部分是第一个元素,'e'. That's the match we found in the string
。那是我们在字符串中找到的匹配'yazeed'.

But my name has two e's! How do we match the other one?
但我的名字有两个e!我们如何匹配另一个?

Regular Expressions (Regex) {#regularexpressionsregex}

The
.match method's first parameter can instead be a
方法的第一个参数可以改为a regular expression .

Regular Expression - A sequence of characters that define a search pattern. Also known as "Regex".
正则表达式 - 定义搜索模式的字符序列。也被称为"正则表达式"。

Instead of quotation marks for a string, put your parameter between forward slashes.
而不是字符串的引号,将参数放在正斜杠之间。

myName = 'yazeed';

myName.match(/e/);
// ["e", index: 3, input: "yazeed", groups: undefined]

We get the same result so who cares? Well check this out, regex allows us to add
我们得到相同的结果,所以谁在乎?好吧,看看这个,正则表达式允许我们添加 flags .

Regex Flag - An indicator that tells Regex to do something special.
正则表达式标志 - 指示正则表达式执行特殊操作的指示器。

myName = 'yazeed';

myName.match(/e/g);
// ^^ Notice the little g now ^^
// ["e", "e"]

We got back all the e's! If you try an a or z, you get an array of just one match. Makes sense.
我们收回了所有的电子邮件!如果您尝试a或z,则只能获得一个匹配的数组。说得通。

myName.match(/a/g);
// ["a"]

myName.match(/z/g);
// ["z"]

Finding all alphanumeric characters {#findingallalphanumericcharacters}

So regex not only matches patterns, but it can match
因此正则表达式不仅匹配模式,而且可以匹配 many of the same kind of pattern! This sounds perfect for our algorithm's next step.
同样的模式!这对于我们的算法的下一步来说听起来很完美。

If you Google a bit, this may be the regex you find for matching all alphanumeric characters.
如果你有点谷歌,这可能是你找到匹配所有字母数字字符的正则表达式。

/[a-z0-9]/g

You're looking at the definition of
你正在看的定义 alphanumeric . This regex can be broken into 3 parts.
。这个正则表达式可以分为3个部分。

  1. A character set [] - match any character between these brackets. character-sets
  2. a-z - match all lowercase letters a-z
  3. 0-9 - match all numbers 0-9

Running it on
运行它myName returns an array of every letter.
返回每个字母的数组。

myName = 'yazeed';

myName.match(/[a-z0-9]/g);
// ["y", "a", "z", "e", "e", "d"]

Let's try it with one of the project's test cases. How about this crazy one they expect to be a palindrome?
让我们尝试一下项目的测试用例。他们期望成为一个回文疯狂的人怎么样?

crazyInput = '0_0 (: /-\ :) 0-0';

crazyInput.match(/[a-z0-9]/g);
// ["0", "0", "0", "0"]

Wow without the crazy characters it's just four zeroes. Yep that's a palindrome! I'll update our code.
哇没有疯狂的角色,它只有四个零。是的,这是一个回文!我会更新我们的代码。

function palindrome(str) {
  const alphanumericOnly = str
        // 1) Lowercase the input
        .toLowerCase()
        // 2) Strip out non-alphanumeric characters
        .match(/[a-z0-9]/g);
  
  // 3) return string === reversedString
}



palindrome("eye");

Executing Step 3 - Compare String to Its Reverse {#executingstep3comparestringtoitsreverse}

Remember that
记住这一点.match returns an
返回一个 array of matches. How can we use that array to compare our cleaned up string to its reversed self?
比赛我们如何使用该数组来比较我们清理后的字符串与其反向自我?

Array.reverse {#arrayreverse}

The
reverse method, true to its name, reverses an array's elements.
方法,如果名称正确,则反转数组的元素。

[1, 2, 3].reverse();
// [3, 2, 1]

This looks pretty useful! After matching all alphanumeric characters, we can flip that array and see if everything still lines up.
这看起来很有用!匹配所有字母数字字符后,我们可以翻转该数组,看看是否所有字符串都排成一行。

But comparing arrays isn't as straightforward as comparing strings, so how can we turn that array of matches back into a string?
但是比较数组并不像比较字符串那么简单,那么我们如何才能将匹配数组转换回字符串呢?

Array.join {#arrayjoin}

The
join method stitches your array's elements together into a string, optionally taking a
方法将数组的元素拼接成一个字符串,可选择取一个 separator .

The separator is the first parameter, you don't need to supply it. It'll basically "stringify" your array.
分隔符是第一个参数,您不需要提供它。它基本上会"串化"你的数组。

[1, 2, 3].join();
// "1,2,3"

If you do supply it, the separator goes in between each element.
如果您提供它,分隔符将介于每个元素之间。

[1, 2, 3].join('my separator');
// "1my separator2my separator3"

[1, 2, 3].join(',');
// "1,2,3"

[1, 2, 3].join(', ');
// "1, 2, 3"

[1, 2, 3].join('sandwich');
// "1sandwich2sandwich3"

Let's see how this would fit into our algorithm.
让我们看看它如何适合我们的算法。

'Ra_Ce_Ca_r   -_-'
    .toLowerCase()
    .match(/[a-z0-9]/g)
    .join('');

// "racecar"

See how doing all that simply recreates the original string without punctuation or mixed casing?
看看如何简单地重新创建没有标点符号或混合套管的原始字符串?

What if we reverse it?
如果我们扭转它怎么办?

'Ra_Ce_Ca_r   -_-'
    .toLowerCase()
    .match(/[a-z0-9]/g)
    // flip it around
    .reverse()
    .join('');

// "racecar"

That's a palindrome! My name would not be a palindrome.
这是一个回文!我的名字不会是回文。

'yazeed'
    .toLowerCase()
    .match(/[a-z0-9]/g)
    // flip it around
    .reverse()
    .join('');

// "deezay"

Seems we have our solution. Let's see the final code.
似乎我们有解决方案。我们来看看最终的代码。

The Final Code {#thefinalcode}

function palindrome(str) {
    const alphanumericOnly = str
        // 1) Lowercase the input
        .toLowerCase()
        // 2) Strip out non-alphanumeric characters
        .match(/[a-z0-9]/g);
        
    // 3) return string === reversedString
    return alphanumericOnly.join('') ===
        alphanumericOnly.reverse().join('');
}



palindrome("eye");

Input this and run the tests, and we're good!
输入这个并运行测试,我们很好!

all-tests-passed

Summary {#summary}

  1. Lowercase input via str.toLowerCase();
  2. Match all alphanumeric characters using a regular expression via str.match(/[a-z0-9]/g).
  3. Use Array.reverse and Array.join on the alphanumeric matches to compare the original against its reversed self. If they're identical we get back true, otherwise we get back false!

Thanks for reading {#thanksforreading}

If you'd like a video with even more detail,
如果你想要一个更详细的视频,here's the YouTube version again!

For more content like this, check out https://yazeedb.com. And please let me know what else you'd like to see!
有关此类更多内容,请访问https://yazeedb.com。请告诉我你还想看到什么!My DMs are open on Twitter.

Until next time!
直到下一次!

中英文模式阅读
中文模式阅读
英文模式阅读

查看英文原文

查看更多文章

公众号:银河系1号
公众号:银河系1号

联系邮箱:public@space-explore.com
联系邮箱:public@space-explore.com

(未经同意,请勿转载)
(未经同意,请勿转载)