zoukankan      html  css  js  c++  java
  • 最长不含有重复字符的子字符串

    题目

      请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含‘a’~‘z’的字符。例如,在字符串“arabcacfr”中,最长的不含重复字符的子字符串是“acfr”,长度为 4

    思路

      定义函数f(i)表示以第i个字符结尾的不包含重复字符的子字符串的最长长度,从左到右扫描,计算第i个字符串结尾的不包含重复的字符的子字符串的最长长度时f(i)时,已经知道f(i-1);

    1.   如果第i个字符之前没有出现过,那么f(i)=f(i-1)+1;
    2.   若果第i个字符之前出现过,那么先计算第i个字符和他上次出现在字符串中的位置距离,记为d

          1>.如果d<=f(i-1),意味着在第i个字符出现两次所夹得字符串串中间没有其他字符,第i个字符出现在f(i-1)所对应的最长字符串中。即f(i)=d;

          2>.如果d>f(i-1),此时第i个字符出现在f(i-1)对应的最长子字符串之前,所以仍然有f(i)=f(f-1)+1;

    #include <iostream>
    #include <cmath>
    #include <vector>
    using namespace std;
    
    class Solution
    {
        public:
            int max_str_duplication(const string &s);
    };
    int Solution::max_str_duplication(const string &s)
    {
        if(s.empty()||s.length()<=0)
            return -1;
    
        int max_len=0;
        int curr_len=0;
    
        //每个字符上次出现在字符串位置中的下标,-1是没有出现过
        vector<int> position(26,-1);
        for(int i=0;i<s.length();++i)
        {
            int per_index=position[s[i]-'a'];//先获取每个字符第一次出现的位置
            if(per_index<0||i-per_index>curr_len)//该字符没有出现过或者在f(i-1)之前出现过
                ++curr_len;
            else//在第个字符和f(i-1)之间出现
            {
                max_len=max(max_len,curr_len);
                curr_len=i-per_index;
            }
            position[s[i]-'a']=i;
        }
        return max(max_len,curr_len);
    }
    int main()
    {
        string str;
        cin>>str;
        Solution s;
        cout<<s.max_str_duplication(str)<<endl;
        return 0;
    }
  • 相关阅读:
    vue element-admin 清空校验
    vue+elementui 动态改变表单必填项
    什么是中台
    项目中遇到的一道算法题
    【解决】Word中公式突然乱码
    【解决】MATLAB报错:此上下文中不支持函数定义,请在代码文件中创建函数。
    【解决】Word打印成PDF出错:%%[ ProductName: Distiller ]%%
    Bike Sharing Analysis(二)- 假设检验方法
    Bike Sharing Analysis(一)- 探索数据
    Spark Structured Streaming(二)实战
  • 原文地址:https://www.cnblogs.com/tianzeng/p/10258973.html
Copyright © 2011-2022 走看看