解题思路
坦白说这个题我不会(微笑,我好菜),把 LeetCode 官方在知乎上的解答和 JAVA 代码写成了 Scala 实现了一遍(再次微笑),代码如下:
object Solution {
def longestPalindrome(s: String): String = {
if(s=="") ""
else{
var (start, end) = (0,0)
val max = (x:Int, y:Int) => if(x>=y) x else y
for(i <- 0 until s.length){
val len1 = expandAroundCenter(s,i,i)
val len2 = expandAroundCenter(s,i,i+1)
val len = max(len1, len2)
if(len> end-start){
start = i - (len-1)/2
end = i+len/2
}
}
s.substring(start,end+1)
}
}
def expandAroundCenter(s:String, left:Int, right:Int):Int = {
var L = left
var R = right
while(L >= 0 && R<s.length() && s.charAt(L) == s.charAt(R)){
L -= 1
R += 1
}
R-L-1
}
}