【问题标题】:How to get word from array which character in it appearing exactly two times如何从数组中获取单词中的哪个字符恰好出现两次
【发布时间】:2021-08-06 17:08:16
【问题描述】:

我的数组包含字符串。我必须一个一个地阅读单词并输出其中包含任何字符的单词恰好出现两次。但我的代码也显示 3 个或更多相同的字符。如何输出只有字符出现两次的单词?例如不显示:"aaaa""aaab"

const words = [
  "asdf",
  "fdas",
  "asds",
  "d fm",
  "dfaa",
  "aaaa",
  "aabb",
  "aaabb"
];

function checkString(text,index){
    if((text.length - index) == 0 ){ //stop condition
        return false; 
    }else{
        return checkString(text,index + 1) 
        || text.substr(0, index).indexOf(text[index])!=-1;
    }
}

// example Data to test

for(var idx in words){
    var txt = words[idx];
  
  if(checkString(txt,0)) {
    console.log(txt);
  }
  
}
const words = [
  "asdf",
  "fdas",
  "asds",
  "d fm",
  "dfaa",
  "aaaa",
  "aabb",
  "aaabb"
];

/*
Output have to be :
asds
dfaa
aabb
aaabb
*/

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以构建一个对象,将输入字符串中的字母映射到它在其中出现的位置,然后根据它们是否出现两次来过滤这些字母:

    const checkString = (inputString) => {
      // Build an empty object
      const occurrences = {};
      for (let char of inputString) {
        // For each character in the input string, add one to its occurrence count
        // If it has never appeared until now, occurrences[char] + 1 will evaluate
        // to NaN, and Nan || 1 is 1
        occurrences[char] = occurrences[char] + 1 || 1;
      }
    
      // Get the characters appearing in the string
      const charsInInputString = Object.keys(occurrences);
      // Extract only the characters appearing exactly twice
      const charsAppearingTwice = charsInInputString.filter(
        (char) => occurrences[char] === 2
      );
      // Return true if there is at least one such character
      return charsAppearingTwice.length > 0;
    };
    

    您的最终正确单词数组将是words.filter(checkString)

    如果您想将单词格式化为单个字符串,使用空格分隔符,可以使用.join 方法:

    const checkedWords = words.filter(checkString).join(" "); // = asds dfaa aabb aaabb
    

    【讨论】:

      【解决方案2】:

      更好的方法是编写一个函数,该函数接受一个字符串并计算它包含的每个字符的数量,然后检查是否有一个字符恰好出现了两次。

      类似的东西

      function checkString(text){
          const charAppearances = {};
          text.split('').forEach( character => {
             charAppearances[character] = (charAppearances[character] || 0) + 1
         })
          return Object.values(charAppearances).includes(2);
      }
      
      

      charAppearances 的目的是计算一个字符出现的次数,例如对于字符串'asdf',它将是{a: 1, s: 1, d:1, f:1}

      forEach 部分迭代字符串的字符并更新当前字符的计数(charAppearances[character] = (charAppearances[character] || 0) + 1 表示“如果character 存在于charAppearances 中,则将其加1,否则将1 加0 ,这将导致 1)

      【讨论】:

        【解决方案3】:

        const words = [ "asdf", "fdas", "asds", "d fm", "dfaa", "aaaa", "aabb", "aaabb" ];
        
        function checkString(text) {
          //create a map to store the frequency of characters
          let map = new Map();
          for(let ch of text){
            if(map.has(ch)){
              map.set(ch, map.get(ch)+1);
            }else{
              map.set(ch, 1);
            }
          }
          
          //now check if frequency of any character is equal to 2
          return [...map.values()].some(x => x == 2);
        }
        
        // example Data to test
        
        for (let txt of words) {
          if (checkString(txt)) {
            console.log(txt);
          }
        }

        【讨论】:

        • Hi Harsh, /* 输出必须是:asds dfaa aabb aaabb */
        • @RuslanBairamovi,固定好友。
        【解决方案4】:

        这是一个考虑分解的好机会。可以使用 reduce (citation) 编写一个计算字符的函数。确定字符串是否包含任何对的问题只是关于第一个问题的狭义问题。基于它的过滤很简单,所以...

        function countsOfCharsIn(string) {
          return [...string].reduce((a, e) => { a[e] = a[e] ? a[e] + 1 : 1; return a }, {}); 
        }
        
        function stringHasAPairOfChars(string) {
          return Object.values(countsOfCharsIn(string)).includes(2)
        }
        
        function stringsWithPairs(array) {
          return array.filter(stringHasAPairOfChars);
        }
        
        const words = [
          "asdf",
          "fdas",
          "asds",
          "d fm",
          "dfaa",
          "aaaa",
          "aabb",
          "aaabb"
        ];
        
        console.log(stringsWithPairs(words));

        【讨论】:

          【解决方案5】:

          下面的实现怎么样?我认为您想排除“aaabb”,因为即使“b”出现两次,“a”也出现了 3 次。但是您在代码末尾的注释包括“aaabb”。在这种情况下,以下实现就足够了。

          const words = [
            "asdf",
            "fdas",
            "asds",
            "d fm",
            "dfaa",
            "aaaa",
            "aabb",
            "aaabb"
          ];
          
          function isAppearingTwoTimes(word) {
            const [...chars] = word; // split chars into the array
            const set = new Set(chars);
          
            if (set.size === word.length)
              return false; // all the chars are unique
          
            return Array.from(set.values()).reduce((accum, ch) => {
              // if found two appearing characters, you don't have to count anymore
              if (accum) return true;
              // counts how many times 'ch' appears in the word 'chars'
              const nums = chars.reduce((counter, c) =>
                c === ch ? counter + 1 : counter, 0);
          
              return nums === 2 || accum;
            }, false);
          
          }
          
          // test the code
          words.forEach(e => {
            if (isAppearingTwoTimes(e)) console.log(e);
          });

          【讨论】:

            【解决方案6】:

            你的方法是如此接近!你唯一需要改变的是,而不是取一个子字符串,只是.split()一个char数组中的所有字符串,并使用.reduce()方法来计算一个char出现在数组中的次数:

            text.split("").reduce((a, char) => char === text[index] ? ++a : a, 0) === 2;
            

            在这里试试

            const words = [
              "afsd",
              "fdas",
              "asds",
              "d fm",
              "dfaa",
              "aaaa",
              "aabb",
              "aaabb"
            ];
            
            function checkString(text,index){
                if((text.length - index) == 0 ){ //stop condition
                    return false; 
                }else{
                    return checkString(text,index + 1) 
                    || text.split("").reduce((a, char) => char === text[index] ? ++a : a, 0) === 2;
                }
            }
            
            // example Data to test
            
            for(var idx in words){
                var txt = words[idx];
              
              if(checkString(txt,0)) {
                console.log(txt);
              }
              
            }

            加号

            • 您可以使用while() 循环来代替递归:

            const words = [
              "afsd",
              "fdas",
              "asds",
              "d fm",
              "dfaa",
              "aaaa",
              "aabb",
              "aaabb"
            ];
            
            
            
            // example Data to test
            
            for (var idx in words) {
              var txt = words[idx];
            
              let state = false,
                thisChar = 0;
                
              while (!state && thisChar < txt.length) {
                txt.split("").reduce((a, char) => char === txt[thisChar] ? ++a : a, 0) === 2 
                && (state = true);
                thisChar++;
              }
              
              if (state) console.log(txt);
            }

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2021-12-12
              • 2014-11-25
              • 2012-12-07
              • 2021-07-30
              • 1970-01-01
              • 2020-12-31
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多