Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Pig Latin

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to achieve Pig Latin". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's ideas to study and learn "how to achieve Pig Latin".

Understand the problem

Recently, there are many problems in the algorithm. I hope to record the process of algorithm analysis with a small question. The title is: Pig Latin

Pig Latin is a way of altering English Words. The rules are as follows: If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add "ay" to it. If a word begins with a vowel, just add "way" at the end.

When faced with a problem with less description, the first reaction is that the simpler the description of the topic, the more hidden conditions will be. Don't panic. Take a look at Wikipedia's explanation of Pig Latin: pig Latin. I like to look at Wikipedia first when looking at the topic. I will understand the background and origin of the topic, so that I can better understand the topic, and at the same time, make it interesting to solve the problem. Simple analysis of the rules: when a word begins with a consonant, move the consonant to the end and add ay, such as

California → aliforniacay: C move to the last and then add ay

Paragraphs → aragraphspay:p move to the last and then add ay

Glove → oveglay:gl moves to the end and then adds ay ⚠️. Here are all the consonants before finding the first vowel.

Vowels: a, e, I, o, u

When a word begins with a vowel, add way directly after the word, such as

Algorithm → algorithmway: an is a vowel, so add way after the word

Eight → eightway: e is a vowel, so add way after the word

After the analysis of the topic, we also need to read the test cases to see if there are any omissions, see the last one:

Should handle words without vowels. TranslatePigLatin ("rhythm") should return "rhythmay".

This rule actually satisfies the first case. When a vowel cannot be found, add ay directly after it.

Analysis process

When we got an algorithm problem, we followed several routines to "attack the city."

1. Algorithm classification, this problem is a string problem, there are no more than two kinds of string operations:

a. Traverse by index

B. Replace replace in particular, there is no emphasis on martial arts morality with regularity.

two。 From shallow to deep:

a. That is to come up and write pseudo-code in the direction of violence according to the given conditions.

b. Looking for key cycle factors and optimization means according to logic

c. Try to optimize

Pseudo code

First write pseudo code, this part of the code is relatively rough, mainly used to sort out the analysis process

VAR STR VAR vowelLetters = ['axiajiaoyu'] / / starting with vowels IF STR [0] in vowelLetters return STR +' way' / / find vowel index FOR (S, INDEX) in STR IF S IN vowelLetters return STR.slice (INDEX) + STR.slice (0meme index) + 'ay' / / there is no vowel renturn STR + ay copy code in the word.

With the analysis process, we can write JavaScript code.

Function translatePigLatin (str) {/ / prepare the array of vowels const vowelLetters = ['axiangjia] / / Special cases: if you start with vowels if (vowelLetters.includes (str [0])) return `$ {str} way` / / normal for (let I = 0; I)

< str.length; i++) { if(vowelLetters.includes(str[i])) { return `${str.slice(i)}${str.slice(0, i)}ay` } } // 如果前面拦不住 说明没有元音 return `${str}ay` } translatePigLatin("consonant"); 复制代码 Review 上面?代码,已经可以通过测试了,那么分析如何优化 。从代码中分析到整个核心的逻辑就落在 ${str.slice(i)}${str.slice(0, i)}ay 那么关键点在于找到 第一个元音的索引那么我们改代码 function translatePigLatin(str) { // 直接找索引 let index = str.split('').findIndex(s =>

/ [aeiou] / .test (s) if (index

< 0)return `${str}ay` if (index === 0)return `${str}way` return `${str.slice(index)}${str.slice(0, index)}ay` } translatePigLatin("consonant"); 复制代码 代码简化一些,逻辑更清晰了 另一条路 从分析过程的路上来看,已经用循环遍历的方法完成了,那么另一条路(replace)应该如何实现?第一种方法的结果来看,需要用到正则分组的方法来调换位置。思路是分两组第一组是开头到元音,第二组是元音到结尾。然后将这两组顺序调换后,添加后缀。在开发和调试正则的时候,推荐 regex101.com/ 来调试正则表达式

Do this through the debugger: / ([^ aeiou] *) (\ w*) / explain

Divide into two groups with two parentheses

([^ aeiou] *) indicates that matches 0 or more characters that are not (^) aeiou.

(\ w*) the remaining characters are a set

Complete the code

Function translatePigLatin (str) {return str.replace (/ ([^ aeiou] *) (\ w*) /,'$2 $1ay')} translatePigLatin ("consonant"); copy the code

Pass the test, huh? The above code has included two cases except that the vowels are not covered at the beginning. At the beginning of the vowel, you need to add the suffix way, that is, when the matching $1 of ([^ aeiou] *) is empty, the suffix becomes ay. The second parameter of the JavaScript string replace method is the String.prototype.replace ()-JavaScript | MDN of the supporting function.

Function translatePigLatin (str) {return str.replace (/ ([^ aeiou] *) (\ w*) /, (_, p1, p2) = > `${p2} ${p1 | |'w'} ay`)} translatePigLatin ("consonant") Copy the code thank you for reading, the above is the content of "how to achieve Pig Latin", after the study of this article, I believe you have a deeper understanding of how to achieve Pig Latin, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report