CodeWars : 新手村练等纪录01- Isograms

Isogram

等级:7kyu

原始题目isogram的解释

An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.

中翻:字串中一个字母只出现一次(不分大小写),若符合条件则回传true(空字串也视为Isogram)。

isIsogram "Dermatoglyphics" == true
isIsogram "aba" == false
isIsogram "moOse" == false -- ignore letter case

自解:

export function isIsogram(str: string){
  let lowerCaseStr = str.toLowerCase(); 
  let arr = lowerCaseStr.split("");
  let setArrNumber = new Set(arr).size
  if(setArrNumber !== arr.length){
    return false
  }
  else{
    return true
  }
}

好像有点冗长,後来查到一位的写法比我精简许多(查看下方),但想法是相同的。
概念是:

  1. 先将字串全部转成lowerCase
  2. 将字串的每个字母拆解
  3. 去比对字母是否有重复,透过new Set()可以让所有的值都是唯一的,若有值重复则会被忽略,
    所以去比较Set完後的元素数量(透过set.prototype.size)是否和原本拆解的字母阵列数量相同,
    若不同则代表有重复字母,回传false,反之则回传true

他解1:

author: fullstackdevguy

export function isIsogram(str: string){
  //resolve str to lowercase first
  str = str.toLowerCase();
  //transform string to a Set to remove duplicates and 
  //compare the size of the set to the length of the str
  return new Set(str.split('')).size === str.length;
}

他解2:

author: stellartux

export function isIsogram (str: string): boolean {
  return (new Set(str.toLowerCase())).size === str.length
}

超级精简的code~~ 十分佩服

此次题目使用到的方法和参考网址:

array.split()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

String.prototype.toLowerCase()
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

Set.prototype.size
https://www.fooish.com/javascript/ES6/Set-and-WeakSet.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/size


<<:  CMoney菁英软件工程师战斗营_Week 7

>>:  C#学习笔记4:C#的基本运算

使用Raspberry pi的相机拍图

前面只用linux 的指令来拍图 现在用Python了 from time import sleep...

求助 Excel VBA 搜寻关键字後贴到其他的tab的写法

各位先备好 如果有一个excel里面资料大概有50列,而每一行都是记载着不同的资讯,譬如:姓名/电话...

【LeetCode】Binary Search Tree

突然发现前面应该要多写一点的@@ 我本来没打算花那麽多篇幅讲 Leetcode... 铁人赛有几篇写...

[Day 14]事件处理v-on

又是一个新的一天又要想今天要打什麽了(;´д`)ゞ,今天打算来讲v-on,以及讲解如何用v-on监听...

CLOUDWAYS虚拟主机限时首二月7折优惠码,只到2021/9/5

优惠码SUMMER30 优惠时间:只到2021/9/5 折扣内容:首2个月7折(适用於所有方案) ☞...