Question is taken from Leetcode and solution works for their test cases. I do see a scope of improvement and make it more functional (getting rid of vars and mutables data structures). Please suggest improvement to help me.
Problem
Given a string, find the length of the longest substring without repeating characters.
Input: "abcabcbb"
Output: 3
Input: "bbbbb"
Output: 1
Input: "pwwkew"
Output: 3
code
import scala.collection.mutable.HashMap
object Solution extends App{
def lengthOfLongestSubstring(s: String): Int = {
if (s.isEmpty) 0
else {
val lookupTable = HashMap[Char,Int]()
var start = 0
var length = 0
for ( (c, i) <- s.zipWithIndex) {
if (!(lookupTable contains c)) {
lookupTable(c) = i
} else {
val newLength = i - start
if (newLength > length) length = newLength
start = lookupTable(c) + 1
lookupTable.retain((k,v) => v >= start)
lookupTable(c) = i
}
}
Math.max(length, (s.length - start))
}
}
Seq("abcabcbb", "pwwkew", "", "nnnn", "b", " ", "aab" , "abca" ,"abba") foreach { s =>
println(s + " = " + lengthOfLongestSubstring(s))
}
}
Output
abcabcbb = 3
pwwkew = 3
= 0
nnnn = 1
b = 1
= 1
aab = 2
abca = 3
abba = 2