找到字符串中"aeiou"的最长出现次数

Leo*_* Li 6 javascript string algorithm node.js

我最近正在接受采访,并被问到多个问题,其中一个问题是这个,我在尝试回答它时遇到了一些麻烦.

给定一个字符串,找出出现的最长的元音"aeiou".元音的子串不必是连续的,并且可以有重复.

目标是找到每个元音的最大出现并加入它们,但它必须是"a","e","i","o","u"的顺序.

编辑:此外,每个单独的元音字符也必须链接.在下面的示例中,有"aaa"和"aa",因为3更长,我们的结果必须包含更长的链.

例如:输入:"aaagtaayuhiejjhgiiiouaae"结果:aaaeiiiou

我尝试过的代码如下:

编辑:在解决方案之后,我在下面写了这个,但我仍然遇到诸如"aeiouaaaeeeiiiooouuu"等字符串的问题.对此的正确结果是15但我得到5.

var findLongestVowels = function(s){
var count = 1;
var i = 0; 
var j = 0;
var vowels = ['a','e','i','o','u'];
var total = 0; 
var array = [];
while (i < s.length){
    if (s.charAt(i) == vowels[j] && s.charAt(i) == s.charAt(i+1) ){
        count++;
    }
    else if (s.charAt(i) == vowels[j] && s.charAt(i) != s.charAt(i+1)){
        if (j === 0 && !array[vowels[j]]){
            array[vowels[j]] = count;
        }
        else if (j === 0 && array[vowels[j]]){
            array[vowels[j]] = Math.max(array[vowels[j]],count);
        }
        else if (j !== 0 && !array[vowels[j]] && array[vowels[j-1]]){
            array[vowels[j]] = array[vowels[j-1]] + count;
        }
        else if (j !== 0 && array[vowels[j]] && array[vowels[j-1]]){
            array[vowels[j]] = Math.max(array[vowels[j]],array[vowels[j-1]] + count);
        }
      count = 1; 
    }
    else if (s.charAt(i) == vowels[j+1] && array[vowels[j]]){
        j++;
        i--;
    }
    i++;
  }
  console.log(array);
  console.log('Answer: ' + array[vowels[j]]);
}

findLongestVowels("eeeeebbbagtaagaaajaaaaattyuhiejjhgiiiouaae");
Run Code Online (Sandbox Code Playgroud)

我至少朝着正确的方向前进吗?

提前致谢.

gur*_*372 0

您需要记住单个元音的最大组合。

使用reduce,map和Object.values

var vowels = "aeiou";
var input = "aaagtaayuhiejjhgiiiouaae";

var output = Object.values( 
  input.split( "" ).reduce( ( a, c, i, arr ) => {
     var lastChar = arr[ i - 1 ];
     if ( !vowels.includes( c ) ) return a; //if not vowel, return accumulator
     if ( c != lastChar ) //if not same as last character then create a new array
     {
         a[ c ] = a[ c ] || [];
         a[ c ].push( [ c ] );
     }
     else //else push to the last array;
     {
         var lastCombo = a[ c ].slice( -1 )[ 0 ];
         lastCombo.push(c)       
     }
     return a; //return accumulator
  } , {}) ).map( s => {
     var char = s[0][0]; //find the character to repeat
     var maxLength = Math.max.apply( null, s.map( s => s.length ) ); //find how many times to repeat
     return Array( maxLength + 1 ).join( char ); 
  }).join( "" ); //join all the vowels
  
console.log( output );
Run Code Online (Sandbox Code Playgroud)