Missing letters——Easy algorithm challenge

problem:

You will create a program that will find the missing letter from a string and return it. If there is no missing letter, the program should return undefined. There is currently no test case for the string missing more than one letter, but if there was one, recursion would be used. Also, the letters are always provided in order so there is no need to sort them.

fearNotLetter("abce") should return "d".
fearNotLetter("abcdefghjklmno") should return "i".
fearNotLetter("bcd") should return undefined.
fearNotLetter("yz") should return undefined.

my solution:

  var arr = [];
  var all;
  for (var i=0; i<str.length; i++) {
    var ins = str.charCodeAt(0);
    if (str.charCodeAt(i) !== (ins + i)) {
      console.log(String.fromCharCode(ins+i));
      all = String.fromCharCode(i+ins);
      break;
    } else {
      all = undefined;
    }
  }
  return all;
}
发现和上次一样,我在进入循环什么时候return出来这里总是做错,或者想的复杂...
总结一下:return之后会直接结束function;如果for循环一变不出return直接外面来return undefined也是可以的。

basic solution:

function fearNotLetter(str) {

  for(var i = 0; i < str.length; i++) {
    var code = str.charCodeAt(i);

    if (code !== str.charCodeAt(0) + i) {
      return String.fromCharCode(code - 1);
    }  
  }
  return undefined;
}

Intermediate Code Solution:

function fearNotLetter(str) {
  var compare = str.charCodeAt(0), missing;

  str.split('').map(function(letter,index) {
    if (str.charCodeAt(index) == compare) {
      ++compare;
    } else {
      missing = String.fromCharCode(compare);
    }
  });

  return missing;
}

Advanced Code Solution:

function fearNotLetter(str) {
  var allChars = '';
  var notChars = new RegExp('[^'+str+']','g');

  for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)
    allChars += String.fromCharCode(str[0].charCodeAt(0) + i);

  return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined;
}

并看不懂我不会到处乱说。好吧我努力拆解一下这个正则是什么意思...

^    匹配字符串的开始
+    重复一次或更多次 
[^x]    匹配除了x以外的任意字符 

a regular expression notChars which selects everything except str

?: Conditional(ternary)Operator

https://developer.mozilla.org...
Syntax:

condition ? expr1 : expr2

Parameters:

condition (or conditions) An expression that evaluates to true or false.
expr1, expr2 Expressions with values of any type.

原文:https://forum.freecodecamp.or...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值