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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值