object TestScala {
/**
*
* @param args
*/
def main(args: Array[String]):Unit={
println("hello , scala!")
var strs:Array[String] = Array("flower","flow","flight")
println(longestCommonPrefix(strs))
strs = Array("dog","racecar","car")
println(longestCommonPrefix(strs))
}
def longestCommonPrefix(strs: Array[String]): String = {
var len:Int = strs.length
//暴力求解,一个一个对比
if(len == 0) //一定要判断输入字符数组是否为非空,不然下面直接取strs(0)就报错了
return ""
var s1:String = strs(0)
for(i <- 1 to len - 1 ){
var len1 = s1.length() //循环里面改了 s1的值,所以也要改s1对应的len1
var s2 = strs(i)
var len2 = s2.length()
var sb:StringBuilder = new StringBuilder
var flag = true //跳出循环
for(j <- 0 to len2 - 1 if flag){
if(j<len1){
if(s1.charAt(j) == s2.charAt(j)){
sb.append(s1.charAt(j))
}else{
flag = false
}
}
}
s1 = sb.toString()
}
s1
}
}