【问题标题】:Write a function which takes a sentence as an input and output a sorted sentence. (The answer should be valid for any given input.)编写一个函数,将一个句子作为输入并输出一个排序后的句子。 (答案应该对任何给定的输入都有效。)
【发布时间】:2020-07-08 15:47:28
【问题描述】:

我想写一个函数,输入一个句子,输出一个排序好的句子,有两个条件:

  1. 单词的每个字符都应该按字母顺序排列。

  2. 单词应根据其字符数按升序排列。

注意:- 单词只能有小写字母

例子:

输入 str = "她和他住在一间小公寓里"

输出 = "a in ehs him hitw eilsv allms aaemnprtt"

这是我的代码。

function makeAlphabetSentenceSort(str) {
  if (!str || str.length === 0) return 0;
  var word = str.split(' ');
  for (var j = 0; j < word.length; j++) {
    word[j] = word[j].split('').sort().join('');
  }
  for (var h = 0; h < word.length - 1; h++) {
    for (var i = 0; i < word.length - h - 1; i++) {
      if (String(word[i]).length > String(word[i + 1]).length) {
        var temp = word[i];
        word[i] = word[i + 1];
        word[i + 1] = temp;
      }
    }
  }
  return word.join(' ');
}

makeAlphabetSentenceSort("she lives with him in a small apartment");

【问题讨论】:

  • 您的代码有什么问题或问题?
  • 问题是,输出对于任何给定的输入都应该是有效的。另外,我想知道当句子包含标点符号时如何工作。例如:“不是吗?”
  • 这是“不是吗?”的正确输出。 => “它安装”
  • 是的 sarvagya8。输出正确。但问题是它应该对任何给定的输入都有效。

标签: javascript sorting


【解决方案1】:

基于输出应仅包含小写字母的假设。

如果你想使用内置函数,你也可以这样写:

function makeAlphabetSentenceSort(str) {
  if (!str) return str;
  const nonCharacters = /[^a-z]/g; // to replace any thing other than letters

  // We split the sentence to words by any whitespace first
  return str.toLowerCase().split(/\s+/).map(word => {
    // Here we remove all non-characters from the word
    // And sort the remaining characters alphabetically
    return word.replace(nonCharacters, '').split('').sort().join('');
    // It might be that the sentence looks like:
    // "Hey! ???"
    // In that case the "word" ??? would become just an empty string
    // since all the non-characters have been removed.
    // But then you would end up with a result:
    // " ehy"
    // because the empty word would still get added to the beginning of the sentence
    // Because of that we need to filter the empty words out
    // And to do that I use this lil trick of mine, using "Boolean"
    // as a filter function since Boolean('') is false
    // and Boolean('any word') is true
  }).filter(Boolean).sort((a, b) => {
    // Here we sort all the words by their length
    return a.length - b.length;
  }).join(' ');
}

console.log(makeAlphabetSentenceSort("Isn't it?"));
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));

【讨论】:

  • 感谢您的回答。但是,这还没有完成我的第三个要求。 => 对于任何给定的输入,答案都应该是有效的。
  • 您能否提供一些您似乎无法使用的输入示例?
  • Ex = > “不是吗?”。我想知道有标点符号时这个功能是否有效。
  • 我更新了处理这种情况的答案(甚至更多!:))检查一下
  • 感谢您的更新回答 :) 当句子中有标点符号时,我测试了该功能。我收到了正确的输出。但问题是我的第三个要求没有满足。 => 对于任何给定的输入,答案都应该是有效的。你能帮我找到那个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
相关资源
最近更新 更多