Accepted 16ms c++ DP solution, O(n), with bitmask to record the last position of each letter appears
class Solution {\n    public:\n        int lengthOfLongestSubstring(std::string s) {\n            std::vector<int> flag(256, -1);\n            int start = 0, lo
    class Solution {\n    public:\n        int lengthOfLongestSubstring(std::string s) {\n            std::vector<int> flag(256, -1);\n            int start = 0, longest = 0;\n            for (int i = 0; i != s.size(); ++i) {\n                start = std::max(start, flag[s[i]] + 1);\n                flag[s[i]] = i;\n                longest = std::max(longest, i - start + 1);\n            }\n            return longest;\n        }\n    };\n\nUpdated **Jun 30**: In fact, there is no need to update `longest` evey time:\n\n    class Solution {\n    public:\n        int lengthOfLongestSubstring(std::string s) {\n            std::vector<int> flag(256, -1);\n            int start = 0, longest = 0, len = s.size();\n            for (int i = 0; i != len; ++i) {\n                if (flag[s[i]] >= start) {\n                    longest = std::max(longest, i - start);\n                    start = flag[s[i]] + 1;\n                }\n                flag[s[i]] = i;\n            }\n            return std::max(longest, len - start);\n        }\n    };
[]