scala Lazness-如何在回文搜索中去掉return语句?
上下文:在大量文本中查找最长的回文 这里有两种解决方案——一种是带有“return”(完全脱离嵌套函数),另一种是蹩脚的“pure”答案。如何编写性能为第一的纯解决方案scala Lazness-如何在回文搜索中去掉return语句?,scala,Scala,上下文:在大量文本中查找最长的回文 这里有两种解决方案——一种是带有“return”(完全脱离嵌套函数),另一种是蹩脚的“pure”答案。如何编写性能为第一的纯解决方案 def isPalindrome(str: String) : Boolean = str.reverse == str def longestPalindrome(haystack : String) : String = { (haystack.length to 1 by -1).foreach{ sub
def isPalindrome(str: String) : Boolean = str.reverse == str
def longestPalindrome(haystack : String) : String = {
(haystack.length to 1 by -1).foreach{ substrSize =>
haystack.sliding(substrSize).foreach{ substr =>
if(isPalindrome(substr))
return substr
}
}
""
}
def longestPalindrome2(haystack : String) : String = {
val x = for {
substrSize <- haystack.length to 1 by -1
substr <- haystack.sliding(substrSize)
} yield (substr -> isPalindrome(substr))
x.find(_._2 == true).map(_._1).getOrElse("")
}
def isPalindrome(str:String):Boolean=str.reverse==str
def longestPalindrome(haystack:String):String={
(haystack.length到1乘以-1).foreach{substrSize=>
haystack.slideing(substrSize).foreach{substr=>
if(isPalindrome(substr))
返回子序列
}
}
""
}
def longestPalindrome2(haystack:String):String={
val x=用于{
substrSize您可以稍微提高第二种方法的性能:
def longestPalindrome3(haystack: String): String =
(for {
substrSize <- haystack.length to 1 by -1
substr <- haystack.sliding(substrSize)
if (isPalindrome(substr))
} yield substr).headOption.getOrElse("")
def longestPalindrome3(haystack:String):String=
(用于{
substrSize您的问题似乎是如何在不使用return
的情况下“短路”计算。一种方法是创建范围的非严格视图
def palindromeStream(haystack : String) = {
for {
substrSize <- (haystack.length to 1 by -1).view
substr <- haystack.sliding(substrSize)
if isPalindrome(substr)
} yield substr
}
val x = palindromeStream("a canal") // Palindromes not yet computed
x.headOption // Compute the first one: Some(ana)
x.toSet // Compute the rest: Set(n, ana, a, " ", l, c)
def回文流(haystack:String)={
为了{
削弱