Если скорость заключается в сделке, идти обязательно.
scala> def longestCommonPrefix(a: String, b: String): String = {
| var same = true
| val sb = new StringBuilder
| var i = 0
| while(same && i < math.min(a.length, b.length)) {
| if(a.charAt(i) != b.charAt(i)) {
| same = false
| } else {
| sb += a.charAt(i)
| i += 1
| }
| }
| sb.result
| }
longestCommonPrefix: (a: String, b: String)String
scala> longestCommonPrefix("", "")
res50: String = ""
scala> longestCommonPrefix("helloworld", "hellohell")
res51: String = hello
РЕДАКТИРОВАТЬ:
Согласно предложению Луиджи:
scala> def longestCommonPrefix(a: String, b: String): String = {
| var same = true
| var i = 0
| while(same && i < math.min(a.length, b.length)) {
| if(a.charAt(i) != b.charAt(i)) {
| same = false
| } else {
| i += 1
| }
| }
| a.substring(0, i)
| }
longestCommonPrefix: (a: String, b: String)String
scala> longestCommonPrefix("helloworld", "hellohell")
res68: String = hello