Longest Substring Without Repeating Characters--LeetCode

来源:互联网 发布:sql去重 编辑:程序博客网 时间:2024/06/04 19:26

1.题目

Longest Substring Without Repeating Characters

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.

2.题意

找到最长无重复子串的长度

3.分析

遍历字符串,得到当前无重复的最新left字符
借助i-left得到最大长度
同时更新每个字符的最新位置

4.代码

class Solution {public:    int lengthOfLongestSubstring(string s) {        vector<int> m(256, -1);        int result = 0, left = -1;        for(int i = 0; i < s.size(); ++i)        {            left = max(left, m[s[i]]);            result = max(result, i - left);            m[s[i]] = i;        }        return result;    }};
阅读全文
0 0