重复字符串中的单词中的字符

时间:2016-02-11 16:39:04

标签: javascript arrays

我正在尝试重写此函数,因此它返回多个值。截至目前,它只返回第一个,所以如果我有一个带有&#34的句子;来自波士顿和#34;的所有人,它只会返回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。顺便说一下,这只是原始线程的解决方案之一,不确定它是否是性能最佳的。

6 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以使用RegEx。

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

RegEx说明:

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

答案 2 :(得分:0)

使用数组函数的强大功能,以下是我将如何解决它:

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()

答案 3 :(得分:0)

你似乎想要一个快速的功能...所以避免多次拆分,映射,减少......等等......你只需要解析一次你的字符串。

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;
}

请这是一个快速片段,未经过全面测试,但它会为您提供另一种方法......

答案 4 :(得分:0)

有点简单。使用来自this answer的dupe finder代码。

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

答案 5 :(得分:0)

这不够吗???

&#13;
&#13;
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;
}
&#13;
<input value="" onchange="alert(returnFirstRepeatChar2(this.value))">
&#13;
&#13;
&#13;

相关问题