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; + } +};