Brian F Love
Learn from a Google Developer Expert focused on Angular, Web Technologies, and Node.js from Portland, OR.
Ad ·ultimatecourses.com.
用终极课程学习角度正确的方式

Hackerrank:让字谜

我把一些样品解决方案放在哈克兰克String: Making Anagramschallenge using JavaScript on Node.js.

I'm really enjoying tackling some (pretty easy) challenges onhackerrank.com.。通过挑战和可能的解决方案思考一切都很有趣,我很享受对同一问题的不同解决方案。如果你想要你也可以看看我的solutions to the array left rotation challenge

In this challenge we are working with anagrams, well, actually we are trying to determine the minimum number of letters that must be removed from two strings to make an anagram. Here is the overview from hackerrank:

给定两个字符串,ab, that may or may not be of the same length, determine the minimum number of character deletions required to makeabanagrams. Any characters can be deleted from either of the strings.

The progam tests expect a single integer output: the number of characters that must be deleted.

资源

You can download the source code and follow along or fork the repository on GitHub:

输入

如给定,输入是表示的两行字符串ab。我创建了一个名为的新文本文件数据。txtthat will represent the input to my program:

ilovea challenge

通过这个给定的输入,我们的Anagram只是:ael。That means that the following letters will be removed:iov从第一个字符串和chlnge从第二个字符串。答案是:9characters need to be deleted from both strings to form the anagram.

I then wrote some code using Node.js to read and parse the data:

//全局变量leta='';letb='';//read standard input处理stdinsetEncoding('utf8');处理stdinresume();//store inputletinput='';处理stdin('数据',功能(数据){input+ =数据;});处理stdin('end',功能(){letlinesOfInput=input分裂('\n');a=linesOfInput[0];b=linesOfInput[1];主要();});//let's do it功能主要(){//verify valuesif(String(a)!==a||String(b)!==b||alength===0||blength===0){throw错误('The input values are invalid.');}//get result//result will be a Number//output处理stdoutwrite(resulttoString());}

First I define some global variables to represent our inputs:ab

I then read the input in via standard input and split the data on the newline character. After saving theabstrings I invoke my主要()功能。

在里面主要()功能我首先验证输入。然后我们将调用一种方法来返回我们的结果,这将是一个数字。最后,我们使用标准输出输出字符串。

First:指数()

我采取的第一种方法将利用array.prototype.indexof()方法。

功能getDeleteCountUsingIndexOf(){varaChars=a分裂('');varBCHAR.=b分裂('');if(aCharslength>BCHAR.length){varouter=aChars;var=BCHAR.;}else{varouter=BCHAR.;var=aChars;}var外面=outerlength-1;(length>0&&outerlength>0&&外面> =0){letinnerindex.=指数(outer[外面]);if(innerindex.!==-1){outersplice(外面,1);splice(innerindex.,1);}-外面;}返回outerlength+length;}

首先,我使用String.prototype.split()method to split the string into an array of characters. I then determine theouter(或更大的阵列)和(shorter) arrays.

I will keep track of my position within theouter数组使用外面, decrementing it after each iteration. While iterating from the end of theouterarray I look for the same character in thearray. If the character exists then I remove the character from both theouterarrays.

The-loop continues until either array is empty (has a length of 0) or the外面is 0.

Second: Destructive

My next approach uses a- 赢得破坏性的方法。这种方法的一个缺点是为了使这个工作,我需要按字母顺序排序字符数组。使用array.prototype.sort()method we can provide a sorting function to sort our arrays. I implement this in a separate function namedgetSortedArrayofChars(str),交流cepts a single string argument and returns the sorted array of characters.

功能getDeleteCountUsingDestructive(){letaChars=getSortedArrayofChars(a);letBCHAR.=getSortedArrayofChars(b);varletters=[];(aCharslength>0||BCHAR.length>0){//check if aChars array is emptyif(aCharslength===0){letterspush(BCHAR.转变());continue;}//check if bChars array is emptyif(BCHAR.[0]===undefined){letterspush(aChars转变());continue;}//shift first element based on ascii comparisonif(aChars[0]<BCHAR.[0]){letterspush(aChars转变());}elseif(aChars[0]>BCHAR.[0]){letterspush(BCHAR.转变());}else{aChars转变();BCHAR.转变();}}返回letterslength;}功能getSortedArrayofChars(str){//get the array of characters using array.split()letarrayOfChars=str分裂('');//sort the array alphabeticallyletalphabetically=(a,b)=>{a=atoloftcase.();b=btoloftcase.();if(a<b){返回-1;}elseif(a>b){返回1;}返回0;};返回arrayOfChars分类(alphabetically);}

Let's break this down:

  • The-loop iterates until both arraysaCharsBCHAR.are empty.
  • We will build an array ofletters其中包含需要从串中删除的字符a要么b为了制作一个字谜。
  • Within the loop I check if either array is empty. IfaCharsarray is empty then all of the characters left in theBCHAR.被推到了letters(as they will need to be removed to form the anagram). And vice versa for theBCHAR.array.
  • 如果位置0的角色aCharsarray is less (lexographically using Unicode) than the character at position 0 in theBCHAR.阵列(例如,a小于b)然后我们使用array.prototype.shift()to remove the element at position 0 in theaCharsarray and to store this value in ourlettersarray.
  • Likewise, if theaChars[0]is greater-thenBCHAR.[0](e.g. b is greater than a) then we remove the first element inBCHAR.和save this inletters
  • 如果字符匹配(例如,a等于a),则可以简单地删除每个阵列中的第一个元素。
  • Once bothaCharsBCHAR.are empty (destroyed) then we return the number ofletters需要删除。

进一步的解释

为了帮助了解破坏性方法,让我们在每次迭代时看一下以下值-loop:

  • aChars- 在给定字符串中排序的字符数组a
  • BCHAR.- 在给定字符串中排序的字符数组b
  • letters- 需要删除以制作字谜的字母(字符)数组。

记住我们的投入是:

ilovea challenge

因此,每个数组的初始值为:

  • aChars=[ 'a', 'e', 'i', 'l', 'o', 'v' ]
  • BCHAR.=[ 'a', 'c', 'e', 'e', 'g', 'h', 'l', 'l', 'n' ]
  • letters=[]

Here is the result of logging the values of each array at the end of each iteration:

aChars: [ 'e', 'i', 'l', 'o', 'v' ] bChars: [ 'c', 'e', 'e', 'g', 'h', 'l', 'l', 'n' ] letters: [] -- aChars: [ 'e', 'i', 'l', 'o', 'v' ] bChars: [ 'e', 'e', 'g', 'h', 'l', 'l', 'n' ] letters: [ 'c' ] -- aChars: [ 'i', 'l', 'o', 'v' ] bChars: [ 'e', 'g', 'h', 'l', 'l', 'n' ] letters: [ 'c' ] -- aChars: [ 'i', 'l', 'o', 'v' ] bChars: [ 'g', 'h', 'l', 'l', 'n' ] letters: [ 'c', 'e' ] -- aChars: [ 'i', 'l', 'o', 'v' ] bChars: [ 'h', 'l', 'l', 'n' ] letters: [ 'c', 'e', 'g' ] -- aChars: [ 'i', 'l', 'o', 'v' ] bChars: [ 'l', 'l', 'n' ] letters: [ 'c', 'e', 'g', 'h' ] -- aChars: [ 'l', 'o', 'v' ] bChars: [ 'l', 'l', 'n' ] letters: [ 'c', 'e', 'g', 'h', 'i' ] -- aChars: [ 'o', 'v' ] bChars: [ 'l', 'n' ] letters: [ 'c', 'e', 'g', 'h', 'i' ] -- aChars: [ 'o', 'v' ] bChars: [ 'n' ] letters: [ 'c', 'e', 'g', 'h', 'i', 'l' ] -- aChars: [ 'o', 'v' ] bChars: [] letters: [ 'c', 'e', 'g', 'h', 'i', 'l', 'n' ] -- aChars: [ 'v' ] bChars: [] letters: [ 'c', 'e', 'g', 'h', 'i', 'l', 'n', 'o' ] -- aChars: [] bChars: [] letters: [ 'c', 'e', 'g', 'h', 'i', 'l', 'n', 'o', 'v' ]

正如你所看到的那样,我们迭代地摧毁aCharsBCHAR.arrays and store an array oflettersthat need to be removed from the array.

资源

您可以在github上下载源代码或fork存储库:

Executing

Executing the solution is easy:

$ node making-anagrams.js<数据。txt

Brian F Love

嗨,我是布莱恩。我对类型名称,Angular和node.js感兴趣我嫁给了我最好的朋友邦妮,我住在波特兰和我滑雪(很多)。