3. Longest Substring Without Repeating Characters(c++) 15ms

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.

思路1:既然是找没有重复的字符串,那么重复字符出现的地方就很重要了,于是使用容器放不重复的字符串,遇到重复的字符就清空重复字符串前的字符。执行时间29ms.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<char> vc;
        int maxlen = 0;
        int n = s.size();
        for (int i = 0; i < n; i++)
        {
            int cc = s[i];
            for (int j = 0; j < vc.size(); j++)
            {
                if (vc[j] == cc)
                {
                    if (maxlen < vc.size())
                    {
                        maxlen = vc.size();
                    }
                    vc.erase(vc.begin(), vc.begin()+j+1);
                    break;
                }
            }
            vc.push_back(cc);
        }
        if (maxlen < vc.size())
        {
            maxlen = vc.size();
        }
        return maxlen;
    }
};

思路2:这个问题实际上是一个动态规划问题,动态规划是通过拆分问题,定义问题状态和状态之间的关系,使得问题能够以递推(或者说分治)的方式去解决。比如这一题,要找没有重复的最长字符串,首先考虑已经找到了第n个字符时最大字符串长度为L,

即S(n)=L,那么遍历第n+1个字符时,如果这个字符已经在前面重复了,可知S(n+1)=L,否则S(n+1)=L+1. 此方法时间复杂度O(n),执行时间15ms.

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> vc(255,-1);//使用vector来记录出现的字符
        int start=-1,maxLen=0;
        for(int i=0;i!=s.size();i++)
        {
            if(vc[s[i]]>start)
                start = vc[s[i]];
            vc[s[i]]=i;
            maxLen = max(maxLen,i-start);
        }
        return maxLen;
    }
};
原文地址:https://www.cnblogs.com/nice-forever/p/6256592.html