Leetcode 3. Longest Substring Without Repeating Characters (Medium) (cpp)

来源:互联网 发布:软件精灵下载安装 编辑:程序博客网 时间:2024/05/22 06:31

Leetcode 3. Longest Substring Without Repeating Characters (Medium) (cpp)

Tag: Hash Table, Two Pointers, String 

Difficulty: Medium


/*3. Longest Substring Without Repeating Characters (Medium)Given a string, find the length of the longest substring without repeating characters.Examples:Given "abcabcbb", the answer is "abc", which the length is 3.Given "bbbbb", the answer is "b", with the length of 1.Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.*/class Solution {public:    int lengthOfLongestSubstring(string s) {        int start = 0, max_len = 0;        vector<int> last_position(255, -1);        for (int i = 0; i < s.size(); i++){            if (last_position[s[i]] >= start){                max_len = max(i - start, max_len);                start = last_position[s[i]] + 1;            }            last_position[s[i]] = i;        }        return max((int)s.size() - start, max_len);    }};


0 0