题目一 Consonant value

658 阅读2分钟

昨天我在CodeWar上做到一个6kyu的题目还算有趣。分享给大家。

Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except "aeiou".

We shall assign the following values: a = 1, b = 2, c = 3, .... z = 26.

For example, for the word "zodiacs", let's cross out the vowels. We get: "z o d ia cs"

-- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22. The highest is 26.
solve("zodiacs") = 26

For the word "strength", solve("strength") = 57
-- The consonant substrings are: "str" and "ngth" with values "str" = 19 + 20 + 18 = 57 and "ngth" = 14 + 7 + 20 + 8 = 49. The highest is 57.

For C: do not mutate input.

More examples in test cases. Good luck!

这个题目的大意就是说给定的字符串中把每一个字母在字母表中的位置如a = 1, b = 2加起来。但是元音字母(aeiou)把字母和字母分隔开,取这分开字符串按照上述方法计算的最大值。

我第一眼看到这个题目的时候就想到定义两个值 一个保存遍历值,一个保存最终结果。

那么如何避开元音字母呢?

我想到

[...s].forEach(function(ele){ if(![a,e,i,o,u].includes(ele)))};

就这样避开元音字母,但别忘了遍历字符串中还要进行数值之间的比较,每次碰到元音就要比较数值。 那么这道题就完成了。

真的结束了吗?没有!!!

这个代码有很多if判断,这让我很不爽。有没有更简洁,判断更少的解题方法。那必须有!

我想到既然这个字符串里有元音隔开,那么我们一不做二不休,把这个字符串化为每个元素都只有辅音的数组。

s.split(/[aeiou]/g)

是的没错,split函数可以放字符串的参数也可以使用正则表达式。这样对于字符串"zodiacs",就会转化为

["z", "", "d", "", "cs"]

我们还需要求出每个元素中每个字母在表里位置。我的最后解法如下。

function solve(s) {
  s = s.split(/[aeiou]/g).map(function(ele){ 
   return [...ele].reduce((a,b) => a + b.charCodeAt() - 96, 0);
  })
  return Math.max(...s);
};

第一种解法是这样

function solve(s) {
  let highest = 0
  let sum = 0
  
  for (const char of s) {
    if (isConsonant(char)) {
      sum += getValue(char)
      
      if (highest < sum) {
          highest = sum
      }
    } else {
      sum = 0
    }
  }  
  
  return highest
};

function getValue(char) {
  return char.charCodeAt(0) - 97 + 1
}

function isConsonant(char) {
  return !'aeiou'.includes(char)
}

之所以放弃这种方法是,大家对于在循环中做判断的厌恶,而且相比之下,我的最终解法更为简洁。

当我提交之后,我看到了大佬,一行超人。

const solve = s => s.split(/[aeiou]+/).reduce((s,n)=> Math.max(s, n.split('').reduce((a,b)=> a + b.charCodeAt(0)-96,0 )), 0);

瞬间感觉自己和大佬之间的差距。心累。虽然思路是一样的。

但是自己还需要继续加油啊!奥里给!