查找元音的最长子串

时间:2018-07-05 14:32:05

标签: javascript html arrays regex

我在用户输入字符串的地方输入内容,我需要在该字符串中找到最长的元音链并将其呈现出来。我自己尝试过,但是不确定如何做。这是我的代码:

vowelHandler = () => {
    let input = document.getElementById('input2'); 
    const hasVowel = /[aeiouAEIOU]/g;
    let letters = []; 
    let vowels = ''; 
    let count = 0;
    let res = 0;
    letters = input.value.match(/[aeiouAEIOU]/g); 
    if(hasVowel.test(letters)) { 
      for(let i = 0; i <= letters.length; i++) {
        if(hasVowel.test(letters[i])) {
          count++;
          res = Math.max(res, count);
        }else {
          res = Math.max(res, count);
          count = 0;
        }
      }
      letters = letters.join(' ');
      vowels = letters.substring(letters[res]);
      document.getElementById('num2').innerHTML= vowels;
    }else {
      document.getElementById('num2').innerHTML= 'String does not contain vowels.';
    }
  }
<input type='text' id='input2'/>
<button onClick={this.vowelHandler}>CLICK</button>
<p id='num2'></p>

3 个答案:

答案 0 :(得分:4)

您可以将字符串中不是元音的所有内容替换为空格,将字符串除以空格,然后检查这些子字符串中最长的子字符串。

function getLongestVowelSubstring(s) {
  const separateVowels = s.replace(/[^aeiou]/ig, ' ').split(' ');

  const longest = separateVowels.reduce((longest, vowelGroup) => {
    return vowelGroup.length > longest.length ? vowelGroup : longest;
  }, '');

  return longest;
}

console.log(getLongestVowelSubstring('get the looongest vowel substring'));

答案 1 :(得分:2)

尝试这样的事情:

vowelHandler = () => {
    let input = document.getElementById('input2'); 
    const hasVowel = /[aeiouAEIOU]+/g;
    const letters = input.value.match(hasVowel);
    if (letters) {
        const longest = letters.reduce((acc, val) => acc.length > val.length ? acc : val, '');
        document.getElementById('num2').innerHTML= longest;
    } else {
        document.getElementById('num2').innerHTML= 'String does not contain vowels.';
    }
}

答案 2 :(得分:2)

使用以下工作示例:

let vowels = ['a', 'e', 'i', 'o', 'u']
function largestVowel(inputStr) {
  let largestStr = '';
  let tempVowelStr = '';
  inputStr.split('').forEach(char => {
    if (vowels.includes(char.toLowerCase())) {
      tempVowelStr += char;
      if (tempVowelStr.length > largestStr.length) {
        largestStr = tempVowelStr;
      }
    } else {
      tempVowelStr = '';
    }
  })
  return (largestStr.length === 0) ? 'String does not contain vowels.' : largestStr;
}

console.log(largestVowel('ertyyfouigdg'));

console.log(largestVowel('sdfsfsf'));

console.log(largestVowel('sdeefsfiaeosf'));

复杂度: O(n)