From d74b6a5d39bae76ea0d079d6a5b1427ca2e213b5 Mon Sep 17 00:00:00 2001 From: Creative15305 Date: Fri, 24 Oct 2025 23:14:39 +0530 Subject: [PATCH] Implement lengthOfLongestSubstring function --- lengthOfLongestSubstring.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 lengthOfLongestSubstring.py diff --git a/lengthOfLongestSubstring.py b/lengthOfLongestSubstring.py new file mode 100644 index 0000000..d30e840 --- /dev/null +++ b/lengthOfLongestSubstring.py @@ -0,0 +1,24 @@ +#include +using namespace std; + +class Solution { +public: + int lengthOfLongestSubstring(string s) { + vector index(256, -1); // stores last index of each character + int maxLen = 0; + int start = 0; // left boundary of current window + + for (int end = 0; end < s.size(); end++) { + char c = s[end]; + + // If character was seen before and is inside the current window + if (index[c] >= start) + start = index[c] + 1; + + index[c] = end; // update last index of this char + maxLen = max(maxLen, end - start + 1); + } + + return maxLen; + } +};