My easy c++ code using string built in method in O(n) time (24 ms)


  • 0
    S
    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int len = 0;
    		string buf;
    		for (size_t i = 0; i < s.length() ;i++)
    		{
    			int pos = buf.find(s[i]);
    			if (pos>=0)
    			{
    				len = len >= buf.length() ? len : buf.length();
    				buf.erase(buf.begin(), buf.begin() + pos + 1);
    			}
    			buf += s[i];
    		}
    		return len >= buf.length() ? len : buf.length();
        }
    };

  • 0
    N

    I think buf.find(s[i]) may return an unknown number when no target letter found.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.