23-Longest Substring Without Repeating Characters

来源:互联网 发布:乔治亚当斯基事件知乎 编辑:程序博客网 时间:2024/06/16 08:58

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.

本题:中等难度
思路:动态规划

f[j]j
f[j]={f[j1]+1f[j1]num+1A[j]notinvs[j1]A[j]invs[j1]

其中vs[j-1]保存连续子串,num表示去掉重复字符(包含)之前的字符$$

class Solution {public:    int lengthOfLongestSubstring(string s) {        int n = s.size();        if(n<=1)return n;        vector<vector<char> > vm(n);        vector<int> vi(n);        vi[0]=1;        vm[0].push_back(s[0]);        for(int i=1;i<n;++i)        {            vector<char>::iterator  it= find(vm[i-1].begin(),vm[i-1].end(),s[i]);            if(it!=vm[i-1].end())            {                vector<char> vtmp(it+1,vm[i-1].end());                vm[i]=vtmp;                vm[i].push_back(s[i]);                vi[i]=vm[i-1].end()-it;            }            else{                vi[i]=vi[i-1]+1;                vm[i]=vm[i-1];                vm[i].push_back(s[i]);            }        }        return *max_element(vi.begin(),vi.end());    }};
0 0