在一个单词字符串中找到最短的单词

3

我又在做 Code-Wars 挑战了,对于这个特定的挑战,我有一个问题:

任务:“给定一个单词字符串,返回最短单词的长度(们)。”

字符串永远不会为空,并且您不需要考虑不同的数据类型。

我查看了 SO 上可用的答案,并根据外部思路成功创建了程序。

问题是它仍然不能产生所需的输出。

我审查了代码,认为问题在于变量以及我无法正确分配代码的正确部分。(尽管我可能错了)

因此,下面我附上代码和测试。

希望你们中的任何一个都能找到问题的答案。

干杯

object Shortest{
  def findShort(str:String):Int ={

    var smallestLength = 99
    var currentLength = 0

    for(word <- str.split("")) {
      currentLength = 0

      for(letter <- word){
        currentLength +=1
      }

      if(currentLength < smallestLength)
        smallestLength = currentLength         
    }
    smallestLength            
  } 
}

以下是测试结果:

ShortestTest findShort(比特币可能接管世界,也许谁知道)应返回3

测试失败 1不等于3 堆栈跟踪 完成时间为45ms findShort(原来随机测试案例比编写基本测试案例更容易)应返回3 测试失败

1不等于3 堆栈跟踪 完成时间为1ms findShort(让我们谈一谈最好的语言 JavaScript)应返回3 测试失败 1不等于3 堆栈跟踪 完成时间为1ms findShort(我希望有一天环游世界写代码)应返回1 findShort(让我们去一个非常寒冷的地方度假)应返回2 测试失败

1不等于2 堆栈跟踪 完成时间为1ms findShort(Steem Dogecoin 21inc Dash MadeSafeCoin)应返回4 测试失败

1不等于4 堆栈跟踪 完成时间为1ms findShort(Bitcoin Lisk)应返回4 测试失败 1不等于4 堆栈跟踪 完成时间为1ms findShort(ProofOfStake Ripple)应返回6 测试失败

1不等于6 堆栈跟踪 findShort(ProofOfWork Dogecoin BTC Classic Dash Ripple ProofOfWork)应返回3 测试失败

1不等于3 堆栈跟踪 完成时间为1ms findShort(LiteCoin Bitcoin LiteCoin Bitcoin Waves Waves Bitcoin Dash Ripple Ripple Ethereum Classic Factom LiteCoin Factom Waves Factom)应返回4 测试失败

1不等于4 堆栈跟踪 完成时间为2ms findShort(Bitcoin Waves MadeSafeCoin DarkCoin ProofOfStake Classic BTC)应返回3 测试失败

1不等于3 堆栈跟踪 完成时间为1ms findShort(ProofOfStake Waves Ethereum Ethereum Ripple LiteCoin Steem Classic LiteCoin Ripple ProofOfStake Steem Monero Dogecoin Factom)应返回5 测试失败


如果您的输入仅包含长度为100或更长的子字符串,会发生什么? - lambda.xy.x
如果你想要一行代码:def f(s:String) = s.split(" ").map(_.length).filter(_ > 0).min - lambda.xy.x
1个回答

4

实际上,您的解决方案是可以的,您只需要将 str.split("") 更改为 str.split(" ")(注意空格)即可。

这是一种依赖于内置方法的方法:

def findShort(wordsString: String): Int = {
  val wordsArray = wordsString.split(" ")
  wordsArray.minBy(_.length).length
}

println(findShort("LiteCoin Bitcoin LiteCoin Bitcoin Waves Waves Bitcoin Dash Ripple Ripple Ethereum Classic Factom LiteCoin Factom Waves Factom"))
// Display 4
println(findShort("Bitcoin Waves MadeSafeCoin DarkCoin ProofOfStake Classic BTC"))
// Display 3

这里提供了一种使用 foldLeft 的版本,如果你不想依赖内置的方法:

def length(word: String): Int =
  word.foldLeft(0){case (acc, _) => acc + 1}

def findShort(str:String):Int = {

   str.split(" ").foldLeft(99){ case (smallestLength, word) =>
      val currentLength = length(word)
      if(currentLength < smallestLength)
         currentLength
       else smallestLength
   }
}

2
isEmpty测试是不必要的,因为split始终会返回一个非空的数组。 - Tim
啊,好的,我刚刚加了一个空格,现在一切都运行得很完美。 - Mateusz Woś
谢谢你提供这两个不同方法的例子,这让我对它有了其他的看法。 - Mateusz Woś

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接