每日一道算法题 - LetterChanges(easy-4)

虽然都是很简单的算法,每个都只需5分钟左右,但写起来总会遇到不同的小问题,希望大家能跟我一起每天进步一点点。
更多的小算法练习,可以查看我的文章。

规则

Using the JavaScript language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string.

使用JavaScript语言,使用函数LetterChanges(str)获取传递的str参数并使用以下算法对其进行修改。
将字符串中的每个字母替换为字母表后面的字母(即 c变为d,z变为a)。
然后将这个新字符串(a,e,i,o,u)中的每个元音大写,并最终返回此修改后的字符串。

测试用例

Input:"hello*3"
Output:"Ifmmp*3"


Input:"fun times!"
Output:"gvO Ujnft!"

Input:"I love Code Z!"
Output:"J mpwf DpEf A!"

my code

function LetterChanges(str) {
    var strArr = ['a', 'e', 'i', 'o', 'u']
    var newStr = ''
  
    for(var i=0;i<str.length;i++) {
      var asciiCode = str[i].charCodeAt(0)
      var tempStr = str[i]
      
      if (asciiCode <= 122 && asciiCode >= 97) {
          asciiCode = asciiCode === 122 ? 97 : asciiCode + 1
          tempStr =  String.fromCharCode(asciiCode)
      }else if(asciiCode <= 90 && asciiCode >= 65) {
          asciiCode = asciiCode === 90 ? 65 : asciiCode + 1
          tempStr =  String.fromCharCode(asciiCode)
      }
  
      if(strArr.indexOf(tempStr) !== -1) {
          tempStr = tempStr.toUpperCase()
      }
      newStr += tempStr
    }
   
    return newStr; 
}

other code

function LetterChanges(str) { 
    str = str.replace(/[a-zA-Z]/g, function(ch) {
        if (ch === 'z') return 'a';
        else if (ch === 'Z') return 'A';
        else return String.fromCharCode(ch.charCodeAt(0) + 1);
    });
   
    return str.replace(/[aeiou]/g, function(ch) {
        return ch.toUpperCase();
    });
}

思路

方法1: 使用ASCII码去判断,a-z(97,122)之间;A-Z(65,90)之间

方法2:使用正则去匹配,特殊情况如”z”和”Z”,返回对应的值

知识点

  1. charCodeAt(),获取字符串的ASCII码
  2. String.fromCharCode(), 把ASCII码转换成字符串
    原文作者:an_l
    原文地址: https://segmentfault.com/a/1190000015575941
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞