Tuesday, 4 October 2016

Longest Substring Without Repeating Characters (LeetCode)

Problem: Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
    map<char, int> hashMap;
    int leftIndex=-1, mx=0;
    for(int i=0;i<s.size();i++)
    {
        if(hashMap[s[i]])
            leftIndex = max(leftIndex, hashMap[s[i]]-1);
        mx = max(mx, i-leftIndex);
        hashMap[s[i]]=i+1;
    }
    return mx;
    }
};

No comments:

Post a Comment