在字母列表中找到丢失的字母

时间:2015-07-10 20:35:10

标签: javascript

我正在尝试解决以下问题:

在传递的字母范围内找到丢失的字母并将其返回。如果范围内存在所有字母,则返回undefined。

我将以字符串形式获得的输入:

  • abce(应返回d)
  • bcd(应返回undefined)
  • abcdefghjklmno(应该返回i)
  • yz(应返回undefined)

我的代码目前看起来像这样:

  function fearNotLetter(str) {
  //create alphabet string
  //find starting letter in alphabet str, using str
  //compare letters sequentially
  //if the sequence doesn't match at one point then return letter
  //if all letters in str appear then return undefined

  var alphabet = ("abcdefgheijklmnopqrstuvwxyz");
  var i = 0;
  var j = 0;
  while (i<alphabet.length && j<str.length) {
    i++;
    if (alphabet.charCodeAt(i) === str.charCodeAt(j)) {
      i++;
      j++;      
    }
    else if (alphabet.charCodeAt(i) !== str.charCodeAt(j)) {
      i++;
      j++;
      if (alphabet.charCodeAt(i) === str.charCodeAt(j-1)) {
        return alphabet.charCodeAt(i-1);  
      }
    }
  }
}

fearNotLetter('abce');

感谢您一如既往的帮助!

17 个答案:

答案 0 :(得分:7)

我会这样做:

&#13;
&#13;
function fearNotLetter(str) {
    var i, j = 0, m = 122;
    if (str) {
        i = str.charCodeAt(0);
        while (i <= m && j < str.length) {
            if (String.fromCharCode(i) !== str.charAt(j)) {
                return String.fromCharCode(i);
            }
            i++; j++;
        }
    }
    return undefined;
}

console.log(fearNotLetter('abce'));        // "d"
console.log(fearNotLetter('bcd'));         // undefined
console.log(fearNotLetter('bcdefh'));      // "g"
console.log(fearNotLetter(''));            // undefined
console.log(fearNotLetter('abcde'));       // undefined
console.log(fearNotLetter('abcdefghjkl')); // "i"
&#13;
&#13;
&#13;

i可以从97到122,此间隔对应ASCII codes of the lower case alphabet

如果您希望它不区分大小写,请在函数开头执行str = str.toLowerCase()

答案 1 :(得分:4)

我认为这是最简单的代码:

&#13;
&#13;
function skippedLetter(str) {
    for (var i = 0; i < str.length - 1; i++) {
        if (str.charCodeAt(i + 1) - str.charCodeAt(i) != 1) {
            return String.fromCharCode(str.charCodeAt(i) + 1);
        }
    }
}

alert(skippedLetter('abce'));
&#13;
&#13;
&#13;

此版本将拒绝非法输入,接受大写和小写,检查范围内只有1个洞,并且确实缺少1个字符。

&#13;
&#13;
function skippedLetter(str) {
    if (!str.match(/^[a-zA-Z]+$/)) return;
    var letter = "", offset = str.charCodeAt(0);
    for (var i = 1; i < str.length; i++) {
        var diff = str.charCodeAt(i) - i - offset;
        if (diff == 1) letter += String.fromCharCode(i + offset++)
        else if (diff) return;
    }
    if (letter.length == 1) return letter;
}

alert(skippedLetter('123567'));		// illegal characters
alert(skippedLetter(''));		// empty string
alert(skippedLetter('a'));		// too short
alert(skippedLetter('bc'));		// nothing missing
alert(skippedLetter('df'));		// skipped letter = e
alert(skippedLetter('GHIKLM'));		// skipped letter = J
alert(skippedLetter('nOpRsT'));		// cases mixed
alert(skippedLetter('nopxyz'));		// too many characters missing
alert(skippedLetter('abcefgijk'));	// character missing more than once
alert(skippedLetter('abcefgfe'));	// out of order
&#13;
&#13;
&#13;

答案 2 :(得分:1)

请注意, @Html.TextBoxFor(model => modelOrdensFinalizadas.DataInicio 中有拼写错误:有两个“e”。

您可以 docs 将字符串转换为数组,然后使用 split 方法将循环短路找到一个匹配:

alphabet

答案 3 :(得分:0)

概述:

 const fearNotLetter = str => {
  if(str.length < 26) {
    return String.fromCharCode( 
      str.split("")
      .map(x=> x.charCodeAt(0))
      .sort((a,b) => a-b)
      .find((x,i,a) => a[i+1]-x > 1) + 1
    );
  }
}

1 衬里:

const fearNotLetter = str => str.length < 26 ? String.fromCharCode(str.split("").map(x=> x.charCodeAt(0)).sort((a,b) => a-b).find((x,i,a) => a[i+1]-x > 1) + 1) : undefined;

答案 4 :(得分:0)

这是我另一个缺少字母的答案:

for f in filenames:
    q, I = np.genfromtxt(fname=f,skip_header=13, skip_footer=0,unpack=True)
    x=q**4
    y=I*q**4
    slope, intercept, r_value, p_value, std_err = linregress(x, y)
    IB = I - slope
    np.savetxt('output_file.txt', (q,Ib))

答案 5 :(得分:0)

  function fearNotLetter(str) {
  //transform the string to an array of characters    
  str = str.split('');

  //generate an array of letters from a to z
  var lettersArr = genCharArray('a', 'z');
  //transform the array of letters to string
  lettersArr = lettersArr.join('');
  //substr the a to z string starting from the first letter of the provided 
  string
  lettersArr = lettersArr.substr(lettersArr.indexOf(str[0]), str.length);
  //transform it again to an array of letters
  lettersArr = lettersArr.split('');
  //compare the provided str to the array of letters
  for(var i=0; i<lettersArr.length;i++){
    if(str[i] !== lettersArr[i])
      return lettersArr[i];
  }
  return undefined;
}

function genCharArray(charA, charZ) {
    var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);
    for (; i <= j; ++i) {
        a.push(String.fromCharCode(i));
    }
    return a;
}

fearNotLetter("bcd");

答案 6 :(得分:0)

我刚刚接受了这个挑战。我是Javascript的初学者,所以这是我的方法,非常简单,有时你不必使用他们提供的方法,但他们也有帮助。我希望你能理解它。

function fearNotLetter(str) {

var alphabet= "abcdefghijlmnopqrstuvwxyz";
var piece =alphabet.slice(0, str.length+1);




for(var i=0; i < piece.length; i++ ){
if(str.charCodeAt(0) != 97){

return undefined;
}

else if(str.indexOf(piece[i])===-1){
  return piece[i];
}
}// for loop

}

fearNotLetter("abce");// It will return d
fearNotLetter("xy");//It will return undefined
fearNotLetter("bce");//It will return undefined

答案 7 :(得分:0)

这是我的解决方案,我觉得很容易理解:

function fearNotLetter(str) {
  var missingLetter;
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) - str.charCodeAt(i-1) > 1) {
      missingLetter = String.fromCharCode(str.charCodeAt(i) - 1);
    }
  }
  return missingLetter;
}

答案 8 :(得分:0)

试试这个:

function fearNotLetter(str) {
    var alp = ('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').split(''), i;
    for (i =  alp.indexOf(str.charAt(0)); i < str.length; i++) {
        if (str.split('').indexOf(alp[i]) === -1) {
            return alp[i];
        }
    }
    return undefined;
}

fearNotLetter('bcd');

答案 9 :(得分:0)

以下是我使用的内容:

function fearNotLetter(str) {
        var firstLtrUnicode = str.charCodeAt(0),
            lastLtrUnicode = str.charCodeAt(str.length - 1);
        var holder = [];
        for (var i=firstLtrUnicode; i<=lastLtrUnicode; i++) {
            holder.push(String.fromCharCode(i));
        }
        var finalStr = holder.join('');
        if ( finalStr === str ) { return undefined; }
        else { return holder.filter( function(letter) {
            return str.split('').indexOf(letter) === -1;
        }).join(''); } }

答案 10 :(得分:0)

这是一个更短的答案,感谢RegExp()允许您动态创建正则表达式并使用match()从生成的字符串中删除给定的字母,该字符串包含所有字母给定范围:

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;

}

答案 11 :(得分:0)

这个怎么样?它会在第一个和最后一个给定字母之间找到所有丢失的字母:

function fearNotLetter(str) {
  var strArr = str.split('');
  var missingChars = [], i = 0;
  var nextChar = String.fromCharCode(strArr[i].charCodeAt(0)+1);
  while (i<strArr.length - 1) {
    if (nextChar !== strArr[i+1]){
      missingChars.push(nextChar);
      nextChar = String.fromCharCode(nextChar.charCodeAt(0)+1);
    } else {
      i++;
      nextChar = String.fromCharCode(strArr[i].charCodeAt(0)+1);
    }
  }

  return missingChars.join('') === '' ? undefined : missingChars.join('') ;
}

console.log(fearNotLetter("ab"));

答案 12 :(得分:0)

&#13;
&#13;
function fearNotLetter(str) {

  var a = str.split('');
  var array = [];
  var j = 0;

  for (var i = 1; i < a.length; i++) {
    var d = a[i].charCodeAt(0);
    var c = a[i - 1].charCodeAt(0);

    var delta = d - c;

    if (delta != 1) {
      array[i] = String.fromCharCode(a[i - 1].charCodeAt(0) + 1);
    }
  }

  str = array.join('');

  if (str.length === 0) {
    return undefined;
  } else {
    return str;
  }
}

fearNotLetter('abcefr');
&#13;
&#13;
&#13;

答案 13 :(得分:0)

我认为你想说如果一个字符串不是以&#34; a&#34;而不是返回&#34; undefined&#34;。所以这是我的代码:

 function fearNotLetter(str) {
   var alphabet = ("abcdefgheijklmnopqrstuvwxyz");
   var i = 0;
   var j = 0;
   while (i < alphabet.length && j < str.length) {
     if (alphabet.charAt(i) != str.charAt(j)) {
       i++;
       j++;
       if (alphabet.charAt(i - 1) == "a") {
         return "undefined";
       } else {
         return (alphabet.charAt(i - 1));
       }
     }
     i++;
     j++;
   }
 }

 alert(fearNotLetter('abce'));

这是工作JsFiddle

您希望代码返回丢失的字母,因此我使用了CharAt 您可以创建一个字母数组,然后搜索它以查看它是否与字符串中的字母匹配....

答案 14 :(得分:0)

这将满足您的需求:

点击运行并检查您的控制台

function missingLetter (str) {
    var alphabet = ("abcdefghijklmnopqrstuvwxyz");
    var first = alphabet.indexOf(str[0]);
    var strIndex = 0;
    var missing;

    for (var i = first ; i < str.length ; i++) {
        if (str[strIndex] === alphabet[i]) {
            strIndex++;
        } else {
            missing = alphabet[i];
        }
    }
    return missing;
}

console.log(missingLetter("abce"));
console.log(missingLetter("bcd"));
console.log(missingLetter("abcdefghjklmno"));
console.log(missingLetter("yz"));

答案 15 :(得分:0)

另一个可能有用的功能:

var alphabet = "abcdefgheijklmnopqrstuvwxyz";
function fearNotLetter(a) {
  function letterIndex(text, index) {
    var letter = text.charAt(0);
    if (alphabet.indexOf(letter) !== index) { return alphabet.charAt(index); } else { return letterIndex(text.substring(1), index + 1) }
  }
  if (alphabet.indexOf(a) === -1) {
    return letterIndex(a, alphabet.indexOf(a.charAt(0)));
  }
  return undefined;
}
fearNotLetter("abc"); //Undefined
fearNotLetter("abce"); //d
fearNotLetter("fgi"); //h

答案 16 :(得分:-1)

git clone