From 352cb09c5456b49123212771118d479f86c014a5 Mon Sep 17 00:00:00 2001 From: Adam Ramos Date: Wed, 20 Jul 2022 12:48:20 -0400 Subject: [PATCH] scala: leetcode scala solution for 3. longest substring without repeating characters --- ...bstring-Without-Repeating-Characters.scala | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 scala/3-Longest-Substring-Without-Repeating-Characters.scala diff --git a/scala/3-Longest-Substring-Without-Repeating-Characters.scala b/scala/3-Longest-Substring-Without-Repeating-Characters.scala new file mode 100644 index 000000000..ba7ec453e --- /dev/null +++ b/scala/3-Longest-Substring-Without-Repeating-Characters.scala @@ -0,0 +1,24 @@ +import scala.collection.mutable + +object Solution { + def lengthOfLongestSubstring(s: String): Int = { + val charMap = mutable.Map[Character, Int]() + var longest = 0 + var left = 0 + var right = left + + while (right < s.length) { + if (charMap.get(s(right)).exists(_ >= left)) { + longest = Math.max(longest, right - left) + + left += 1 + } + else { + charMap.put(s(right), right) + right += 1 + } + } + + Math.max(longest, right - left) + } +} \ No newline at end of file