【问题标题】:Repeating characters in words in a string在字符串中的单词中重复字符
【发布时间】:2016-02-11 16:39:04
【问题描述】:

我正在尝试重做这个函数,所以它返回多个值。到目前为止,它只返回第一个,所以如果我有一个带有“Hello to all from Boston”的句子,它只会返回 Hello,我想改写这个函数,它返回 ["Hello", “全部”,“波士顿”]。

顺便说一句,我从之前的thread得到了这个解决方案。

function returnFirstRepeatChar2(str){
   return ((str = str.split(' ').map(function(word){
     var letters = word.split('').reduce(function(map, letter){
       map[letter] = map.hasOwnProperty(letter) ? map[letter] + 1 : 1;
       return map;
     }, {}); // map of letter to number of occurrence in the word.
     
     return {
       word: word,
       count: Object.keys(letters).filter(function(letter){
         return letters[letter] > 1;
       }).length // number of repeated letters
     };
   }).sort(function(a, b){
     return b.count - a.count;
   }).shift()) && str.count && str.word) || -1; //return first word with maximum repeated letters or -1
}
console.log(returnFirstRepeatChar2("Hello and hello again"));

这里是bin。顺便说一句,这只是原始线程的解决方案之一,不确定它是否是性能最好的解决方案。

【问题讨论】:

  • 您的真正目标是什么?没有真正理解这个问题。
  • @RejithRKrishnan OP 想要打印字符串中包含重复字母的所有单词(hello 有 2 l,all 有 2 l,boston 有 2 o)
  • 我很抱歉,也许我的问题没有很好地表达。我想返回一个包含多个字符的单词数组......所以如果给定字符串“Hello all from Boston”,我会得到结果 ["Hello", "all", "Boston"].. . 但是,如果我在该字符串中有一个包含更多相同字符的单词,例如“Whooooa,Hello all from Boston”,我希望我的数组返回具有最多重复字母的单词,例如 ["whooooa"]

标签: javascript arrays


【解决方案1】:

删除末尾的.shift() - 过滤掉没有重复字母的单词,然后map 结果只返回单词:

function returnFirstRepeatChar2(str){
    return str.split(' ').map(function(word) {
        var letters = word.split('').reduce(function(map, letter) {
           map[letter] = map.hasOwnProperty(letter) ? map[letter] + 1 : 1;
           return map;
         }, {}); // map of letter to number of occurrence in the word.

         return {
             word: word,
             count: Object.keys(letters).filter(function(letter) {
                 return letters[letter] > 1;
             }).length // number of repeated letters
         };
   }).sort(function(a, b) {
       return b.count - a.count;
   }).filter(function(obj) { //Remove words with no dup letters
       return obj.count;
   }).map(function(obj) { //Format the returned result
       return obj.word;
   });
}
console.log(returnFirstRepeatChar2("Hello and hello again")); //["Hello", "hello", "again"] is the result

【讨论】:

  • 感谢您的示例 timeJV... 但快速的问题,如果我介绍另一个单词,比如 4 个相同的字符,例如“ssss”,那应该是数组中唯一的单词,因为没有其他具有四个相同字符的单词,截至目前,该功能正在显示具有 2 个或更多相同字符的任何单词....
【解决方案2】:

您可以使用正则表达式。

str.split(/\s+/) // Split the string by one or more spaces
    .filter(str => /(.).*?\1/.test(str)); // Filter the words containing repeating character

正则表达式解释:

  1. (.):匹配任意单个字符并添加到第一个捕获组中
  2. .*?: 懒惰匹配任意数量的字符,直到条件满足
  3. \1:反向引用。获取 #1 中匹配的字符串,即第一个捕获的组

var str = "Hello to all from Boston";
var arr = str.split(/\s+/).filter(str => /(.).*?\1/.test(str));

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>

现场演示:

var regex = /(.).*?\1/;
document.getElementById('textbox').addEventListener('keyup', function() {
  var arr = (this.value || '').split(/\s+/).filter(str => /(.).*?\1/.test(str)) || [];

  document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
}, false);
<input type="text" id="textbox" />
<pre id="result"></pre>

【讨论】:

  • 不区分大小写,str.split(/\s+/).filter(str =&gt; /(.).*?\1/.test(str.toLowerCase()));
【解决方案3】:

利用数组函数的强大功能,我将如何解决它:

var str = "Hello to all from Boston"

var arr = str.split(" ").filter(function(word) { // for each word in the string
  var cache = {}; // we will check if it has repeated letters
  return word.split("").some(function(letter) { // for each letter in word
    if (cache.hasOwnProperty(letter)) { // if letter was already seen
      return true // return true, the word indeed has repeated letters, stop checking other letters
    };
    cache[letter] = 1; // if not, its the first time we see this letter, mark it
    return false; // and continue with next letter
  }) // if it had repeated letters, we return true, if not we discard it
})

console.log(arr) // ["Hello", "all", "Boston"]

有关所用函数的更多信息:

Array.some()

Array.filter()

【讨论】:

    【解决方案4】:

    您似乎想要一个快速函数...所以避免多次拆分、映射、减少...等...您只需解析一次字符串。

    var parse = (str) => {
        "use strict";
        let i, s, 
            map = {
                word: ""
            }, 
            words = [];
        for (i = 0; s = str[i]; i++) {
            if (s === " ") {
                // end of the previous word
                // if the property "match" is true, the word is a match
                map["match"] && words.push(map["word"]);
                // set map back to an empty object for the next word
                map = {
                    word: ""
                   };
            } else {
                // map[s] already exists, we have a match
                if (map[s]) {
                    map[s] += 1;
                    map["match"] = true;
                // otherwise set to 1 map[s], we have an occurence of s
                } else {
                    map[s] = 1;
                }
                // create the word in match["word"]
                map["word"] += s;           
            }
        }
        // dont forget the last word
        map["match"] && words.push(map["word"]);
        return words;
    }
    

    请这是一个快速的 sn-p,尚未经过全面测试,但它会给您提供另一种方法...

    【讨论】:

      【解决方案5】:

      稍微简单一点。使用来自this answer 的欺骗查找器代码。

      function returnFirstRepeatChar2(str) {
        return str.split(' ').reduce(function (p, c) {
          var hasDupes = c.toLowerCase().split('').sort().join('').match(/(.)\1+/g);
          if (hasDupes) p.push(c);
          return p;
        }, []);  
      }
      
      returnFirstRepeatChar2('Hello to all from Boston'); // [ "Hello", "all", "Boston" ]
      

      DEMO

      【讨论】:

      • 类似于my answer :),但过于冗长。
      • 嗯。我可以忍受它。
      【解决方案6】:

      这还不够吗???

      function returnFirstRepeatChar2(str){
         strA = str.split(' ');
         repeats = [];
         for(i = 0; i < strA.length; i++)
           if( arr = strA[i].match(/([a-zA-Z]).*?\1/) )
             repeats.push(strA[i]);
        return repeats;
      }
      &lt;input value="" onchange="alert(returnFirstRepeatChar2(this.value))"&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        相关资源
        最近更新 更多