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…

    原文作者:yint
    原文地址: https://segmentfault.com/a/1190000010241532
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞