3. Longest Substring Without Repeating Characters——LeetCode OJ

来源:互联网 发布:淘宝网首页登录 编辑:程序博客网 时间:2024/05/17 04:16

Difficulty: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)     {      vector<int> table(256,-1);//字符最近一次出现的位置        int start = -1;//记录最长无重复子串的前一个位置        int maxLength = 0;        for(int i = 0; i < s.length(); ++i)        {            if(table[s[i]] >= start)            {                start=table[s[i]];//最近一次出现位置在start后,重复,更新start            }            table[s[i]] = i;            maxLength = max(maxLength, i-start);        }        return maxLength;    }};

Runtime: 22 ms

阅读全文
0 0
原创粉丝点击